in reply to usage of '+' sign in say statement
G'day seki,
Use of unary plus for disambiguation is common. Here's one instance in which I commonly use it:
$ perl -wE 'say (1 == 0) ? "Yes" : "No"' say (...) interpreted as function at -e line 1. Useless use of a constant ("Yes") in void context at -e line 1. Useless use of a constant ("No") in void context at -e line 1. $ perl -wE 'say +(1 == 0) ? "Yes" : "No"' No
There's nothing special about say:
$ perl -wle 'print (1 == 0) ? "Yes" : "No"' print (...) interpreted as function at -e line 1. Useless use of a constant ("Yes") in void context at -e line 1. Useless use of a constant ("No") in void context at -e line 1. $ perl -wle 'print +(1 == 0) ? "Yes" : "No"' No $ perl -we 'printf (1 == 0) ? "Yes\n" : "No\n"' printf (...) interpreted as function at -e line 1. Useless use of a constant ("Yes\n") in void context at -e line 1. Useless use of a constant ("No\n") in void context at -e line 1. $ perl -we 'printf +(1 == 0) ? "Yes\n" : "No\n"' No
There's also nothing special about the parenthesised list. Here, unary plus is used to disambiguate a hash key:
$ perl -wle 'use constant X => "x"; my %x = (x => 42); print $x{X}' Use of uninitialized value in print at -e line 1. $ perl -wle 'use constant X => "x"; my %x = (x => 42); print $x{+X}' 42
See the CAVEATS section of the constant pragma documentation for more on that.
It's also used to disambiguate a right brace starting a block from one starting a hashref. The map documentation has multiple examples of this.
"Has it a specific meaning there, or is it just an habit with a precise goal in everyday code?"
The code in question works with and without the unary plus:
$ perl -wE 'sub f { @_ } say f(42)' 42 $ perl -wE 'sub f { @_ } say+f(42)' 42 $ perl -wE 'sub f { @_ } say +f(42)' 42
And Perl sees such code as being identical (see B::Deparse if you're unfamiliar with the following usage):
$ perl -MO=Deparse,-p -e 'sub f { @_ } print f(42)' sub f { @_; } print(f(42)); -e syntax OK $ perl -MO=Deparse,-p -e 'sub f { @_ } print+f(42)' sub f { @_; } print(f(42)); -e syntax OK $ perl -MO=Deparse,-p -e 'sub f { @_ } print +f(42)' sub f { @_; } print(f(42)); -e syntax OK
Of course, I can only guess at the original coders intentions:
Finally, a friendly word of caution. You've received a number of replies: I strongly recommend that you take a quick look at "Worst Nodes" before deciding whose advice to take.
— Ken
|
|---|