What is the difference between new Some::Class and Some::Class->new() in Perl?

Using new Some::Class is called “indirect” method invocation, and it’s bad because it introduces some ambiguity into the syntax.

One reason it can fail is if you have an array or hash of objects. You might expect

dosomethingwith $hashref->{obj}

to be equal to

$hashref->{obj}->dosomethingwith();

but it actually parses as:

$hashref->dosomethingwith->{obj}

which probably isn’t what you wanted.

Another problem is if there happens to be a function in your package with the same name as a method you’re trying to call. For example, what if some module that you use‘d exported a function called dosomethingwith? In that case, dosomethingwith $object is ambiguous, and can result in puzzling bugs.

Using the -> syntax exclusively eliminates these problems, because the method and what you want the method to operate upon are always clear to the compiler.

Leave a Comment