In Perl, the difference between class (static) and object (instance) methods is not so strong as in some other languages, but it still exists.
The left operand of the arrow operator ->
becomes the first argument of the method to be called. It may be either a string:
# the first argument of new is string 'Point' in both cases
Point->new(...);
my $class = 'Point';
$class->new(...);
or an object reference:
# reference contained in $point is the first argument of polar_coordinates
my $point = Point->new(...);
my @coord = $point->polar_coordinates;
Class methods are just the ones that expect their first argument to be a string, and object methods are the ones that expect their first argument to be an object reference.
Class methods typically do not do anything with their first argument, which is just a name of the class. Generally, it is only used by Perl itself for method resolution. Therefore, a typical class method can be called for an object as well:
my $width = Point->canvas_width;
my $point = Point->new(...);
my $width = $point->canvas_width;
Although this syntax is allowed, it is often misleading, so it is better to avoid it.
Object methods receive an object reference as the first argument, so they can address the object data (unlike class methods):
package Point;
use strict;
sub polar_coordinates {
my ($point) = @_;
my $x = $point->{x};
my $y = $point->{y};
return (sqrt($x * $x + $y * $y), atan2($y, $x));
}
1;
The same method can track both cases: when it is called as a class or an object method:
sub universal_method {
my $self = shift;
if (ref $self) {
# object logic
...
}
else {
# class logic
...
}
}