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

Methods

A method is a subroutine whose first argument is the object or class it was called on.

In this page:

  1. Methods

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

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
  1. Forgetting to shift $self off @_
  2. Calling a method as a plain function so $self is missing
  3. 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:

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.