Apparent oddity using a subroutine with a multiplication operator

Please could you explain this * apparently * inconsistent behavior for me:

use strict; sub a { 2 + 2 }; print 2 * a(); # this prints: 8 print a() * 2; # this prints: 8 print 2 * a; # this prints: 8 print a * 2; # this prints: 4 

Thanks for the answers, both are very helpful - I learned a lot.

+4
source share
2 answers

In the last example, the expression is parsed as a(*2) , which calls a with the argument glob *2 , which is the short name of the package variable *main::2

If you want a parsed as a function that takes no arguments, you need to declare it as follows:

 sub a () {2 + 2} 

Then perl will parse the statement as you expected. In fact, if you write it like this, perl will determine that it is a constant function, and will be inline 4 anywhere where a would be called.

+6
source

Deparse shows that you pass glob in at the last:

 $ perl -MO=Deparse,-p use strict; sub a { 2 + 2 }; print 2 * a(); # this prints: 8 print a() * 2; # this prints: 8 print 2 * a; # this prints: 8 print a * 2; # this prints: 4 __END__ sub a { use strict 'refs'; 4; } use strict 'refs'; print((2 * a())); print((a() * 2)); print((2 * a())); print(a(*2)); 

Using parens in your routine calls is good ...

+12
source

Source: https://habr.com/ru/post/1340355/


All Articles