Package-Quoted Classes
The final syntactic ambiguity with the indirect object style of method invocation is that it may not be parsed as a method call at all, because the current package may have a subroutine of the same name as the method. When using a class method with a literal package name as the invocant, there is a way to resolve this ambiguity while still keeping the indirect object syntax: package-quote the classname by appending a double colon to it.
$obj = method CLASS::; # forced to be "CLASS"–>method
This is important because the commonly seen notation:
$obj = new CLASS; # might not parse as method
will not always behave properly if the current package has a
subroutine named new or
CLASS. Even if you studiously use the arrow
form instead of the indirect object form to invoke methods, this can, on
rare occasion, still be a problem. At the cost of extra punctuation
noise, the CLASS:: notation guarantees how Perl will parse
your method invocation. The first two examples below do not always parse
the same way, but the second two do:
$obj = new ElvenRing; # could be new("ElvenRing")
# or even new(ElvenRing())
$obj = ElvenRing–>new; # could be ElvenRing()–>new()
$obj = new ElvenRing::; # always "ElvenRing"–>new()
$obj = ElvenRing::–>new; # always "ElvenRing"–>new()This package-quoting notation can be made prettier with some creative alignment:
$obj = new ElvenRing::
name => "Narya",
owner => "Gandalf",
domain => "fire",
stone => "ruby";Still, you may say, “Oh, ugh!” at that double ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access