← Back to Perl Course | Chapter 7: Object-Oriented Perl | Lesson 3 of 7

Methods का उपयोग

एक method एक subroutine है जिसका पहला argument वह object या class है जिस पर यह call हुआ था।

In this page:

  1. Methods

Methods

$obj->method(args) call करना object की class में method lookup करता है और object को पहले argument की तरह pass करता है, जो conventionally $self में store होता है। class name पर एक call, जैसे Class->method, इसकी बजाय class name string pass करता है और class methods के लिए इस्तेमाल होता है। क्योंकि arguments बस @_ हैं, methods अक्सर my ($self, @args) = @_; से शुरू होते हैं।

Note: आप एक variable में stored नाम वाला method $obj->$method_name() से call कर सकते हैं।

उदाहरण: Methods

perl
use strict;
use warnings;

package Counter;

sub new {
    my $class = shift;
    return bless { value => 0 }, $class;
}
sub increment {
    my $self = shift;
    $self->{value}++;
    return $self;
}
sub value { my $self = shift; return $self->{value}; }
sub describe { my $class = shift; return "I am the class $class"; }

package main;

my $c = Counter->new;
$c->increment;
$c->increment->increment;
print "value: ", $c->value, "\n";
print Counter->describe, "\n";
my $method = "value";
print "dynamic call: ", $c->$method(), "\n";

# Output:
# value: 3
# I am the class Counter
# dynamic call: 3
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. @_ से $self shift करना भूल जाना
  2. एक method को plain function की तरह call करना ताकि $self missing हो
  3. किसी ऐसी चीज़ पर -> इस्तेमाल करना जो एक object या class name न हो
चैप्टर सारांश
  • Methods invocant पहले receive करते हैं
  • $self object hold करता है
  • Class->method class name pass करता है
  • $obj->$name() नाम से एक method call करता है
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.