The new Foo
version is called indirect object syntax. It's an old-fashioned way of calling the constructor on a package, and it's discouraged in modern Perl. Here's a partial quote of the relevant section in perldoc.
We recommend that you avoid this syntax, for several reasons.
First, it can be confusing to read. In the above example, it's not
clear if save is a method provided by the File class or simply a
subroutine that expects a file object as its first argument.
When used with class methods, the problem is even worse. Because Perl
allows subroutine names to be written as barewords, Perl has to guess
whether the bareword after the method is a class name or subroutine
name. In other words, Perl can resolve the syntax as either File->new(
$path, $data ) or new( File( $path, $data ) ) .
To parse this code, Perl uses a heuristic based on what package names
it has seen, what subroutines exist in the current package, what
barewords it has previously seen, and other input. Needless to say,
heuristics can produce very surprising results!
Older documentation (and some CPAN modules) encouraged this syntax,
particularly for constructors, so you may still find it in the wild.
However, we encourage you to avoid using it in new code.
The alternative is calling new
as a class method on a package with the arrow, as in Foo->new
. The arrow ->
does three things:
- It looks up what's on its left-hand side. In this case, the bareword
Foo
looks looks like a package name. So Perl will see if it knows a package (or namespace) with that name.
- It calls the method on the right-hand side of the arrow in that package it's just found.
- It passes in the thing that's on the right, which in our case is
Foo
, the package name, as the first argument. That's why in the method declaration you will see my ($class, @args) = @_
or similar.
For all other object oriented calls, it's typical to use the arrow syntax. But there is lots of old code around that uses indirect object syntax for new
, and especially older modules on CPAN still use it in their documentation.
Both work, but the indirect object syntax is discouraged. Use Foo->new
for new code.