http://www.perlmonks.org?node_id=763027


in reply to $obj->method v.s. $obj->method()

There are tools in Perl that allow you to find things like that out by yourself.

The first and easiest (but perhaps not always the most precise) is B::Deparse, which lets perl parse the program, and then reconstructs it from its internal representation. Let's try that:

$ perl -MO=Deparse -ce '$a->method' $a->method; -e syntax OK $ perl -MO=Deparse -ce '$a->method()' $a->method; -e syntax OK

So B::Deparse thinks the two are equivalent.

If you don't trust that, you can get an output of the internal representation of Perl, which is called its op tree with B::Concise:

$ perl -MO=Concise -ce '$a->method()' 7 <@> leave[1 ref] vKP/REFC ->(end) 1 <0> enter ->2 2 <;> nextstate(main 1 -e:1) v:{ ->3 6 <1> entersub[t2] vKS/TARG ->7 3 <0> pushmark s ->4 - <1> ex-rv2sv sKM/1 ->5 4 <#> gvsv[*a] s ->5 5 <$> method_named[PV "method"] ->6 -e syntax OK $ perl -MO=Concise -ce '$a->method' 7 <@> leave[1 ref] vKP/REFC ->(end) 1 <0> enter ->2 2 <;> nextstate(main 1 -e:1) v:{ ->3 6 <1> entersub[t2] vKS/TARG ->7 3 <0> pushmark s ->4 - <1> ex-rv2sv sKM/1 ->5 4 <#> gvsv[*a] s ->5 5 <$> method_named[PV "method"] ->6 -e syntax OK

You don't have to understand its output (neither do I, although I see some sense in some of it), but you can simply compare the two outputs:

$ perl -MO=Concise -ce '$a->method' > a -e syntax OK $ perl -MO=Concise -ce '$a->method()' > b -e syntax OK $ diff a b | wc -l 0

(Don't compare them without a tool, it's too easy to miss a small difference in 2x 8 lines of weird symbols).

So you see that both forms construct the same op tree.

(You don't have to understand the rest of the post, if it confuses you just ignore it).

That said, it's still no 100% proof, because the presence of the parenthesis might affect the parsing of the next term. To check that, you could try the same with

$a->method / 1 # /; $a->method() / 1 # /;

If the parser expects a term, the /.../ part will be parsed as a regexp, if it expects an operator it will parse the slash as the division operator, and the # takes care that the last slash isn't a syntax error. (Yes, I checked it; no, the parens don't make a difference).

Replies are listed 'Best First'.
Re^2: $obj->method v.s. $obj->method()
by perl5ever (Pilgrim) on May 09, 2009 at 15:09 UTC
    This is good info - thanks!