Search⌘ K
AI Features

Indirect Objects

Explore the issues with Perl's indirect object syntax, including parsing ambiguities and limitations with barewords and scalars. Understand why avoiding indirect invocations helps prevent confusing errors and how to use direct method calls for clearer, more reliable Perl code. This lesson guides you through best practices to write maintainable Perl object-oriented code while identifying problematic indirect usage.

Perl isn't a pure object-oriented language. It has no operator new; a constructor is anything that returns an object. By convention, constructors are class methods named new(), but we can name these methods anything we want or even use functions. Several old Perl OO tutorials promote the use of C++ and Java-style constructor calls:

Perl
package Alces {
use Moose;
}
my $q = new Alces; # DO NOT USE

However, they could use the obvious method call:

Perl
package Alces {
use Moose;
}
my $q = Alces->new;

These examples produce equivalent behavior, except when they don’t.

Bareword indirect invocations

In the indirect object form (more precisely, the dative case) of the first example, the method precedes the invocant. This is fine in spoken languages where verbs and nouns are ...