Search⌘ K

Method-Function Equivalence

Explore how Perl's minimal object system treats methods and functions as equivalent constructs. Understand the implications of invoking methods as functions, the risks of bypassing method dispatch, and best practices to avoid common pitfalls in method invocation.

Perl’s object system is deliberately minimal. A class is a package, and Perl doesn’t distinguish between a function and a method stored in a package. The same built-in, sub, declares both. Perl will happily dispatch to a function called as a method. Likewise, we can invoke a method as if it were a function—fully qualified, exported, or as a reference—if we pass in our own invocant manually.

Invoking the wrong thing in the wrong way causes problems.

Caller side

Consider a class with several methods:

Perl
package Order {
use List::Util 'sum';
sub calculate_price {
my $self = shift;
return sum( 0, $self->get_items );
}
...
}

Given an Order object $o, ...