What do you think this code prints if you type in -1 and hit enter?
I was expectingperl -ne'chomp; $x=$_; print "x=$x, -x=",-$x,"\n";'
x=-1, -x=1
which seemed like a reasonable guess.
What I got was
x=-1, -x=+1
The unexpected "+" sign goes away if $x isn't a string, or if you force a numeric context by printing "0-$x" rather than just -$x.
The behaviour is documented in perlop, where it says:
Unary "-" performs arithmetic negation if the operand is numeric. If the operand is an identifier, a string consisting of a minus sign concatenated with the identifier is returned. Otherwise, if the string starts with a plus or minus, a string starting with the opposite sign is returned. One effect of these rules is that "-bareword" is equivalent to "-bareword".
I guess my question is "But why???". This doesn't seem to serve any useful purpose, does it? For instance, if you change the script to read
then the oddity disappears, since $x is no longer a string. That doesn't seem very DWIM-ish to me...perl -ne'chomp; $x=0+$_; print "x=$x, -x=",-$x,"\n";'
Edit: Added bold to highlight the part of the perlop passage I'm questioning...
In reply to Interesting unary - oddity by RMGir
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |