Methods
A method is a subroutine whose first argument is the object or class it was called on.
In this page:
Methods
Calling $obj->method(args) looks up method in the object's class and passes the object as the first argument, which is conventionally stored in $self. A call on the class name, such as Class->method, passes the class name string instead and is used for class methods. Because the arguments are just @_, methods often begin with my ($self, @args) = @_;.
Note:
You can call a method whose name is stored in a variable with $obj->$method_name().
Example: Methods
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
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting to shift $self off @_
- Calling a method as a plain function so $self is missing
- Using -> on something that is not an object or class name
Chapter Summary
- Methods receive the invocant first
- $self holds the object
- Class->method passes the class name
- $obj->$name() calls a method by name
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: