RMGir has asked for the wisdom of the Perl Monks concerning the following question:
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...
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Interesting unary - oddity
by ikegami (Patriarch) on Aug 27, 2004 at 17:11 UTC | |
by hardburn (Abbot) on Aug 27, 2004 at 18:14 UTC | |
by ikegami (Patriarch) on Aug 27, 2004 at 18:38 UTC | |
|
Re: Interesting unary - oddity
by davido (Cardinal) on Aug 27, 2004 at 16:19 UTC | |
by RMGir (Prior) on Aug 27, 2004 at 16:21 UTC | |
by sgifford (Prior) on Aug 27, 2004 at 18:01 UTC | |
|
Re: Interesting unary - oddity
by elwarren (Priest) on Aug 27, 2004 at 21:37 UTC | |
by ikegami (Patriarch) on Aug 28, 2004 at 07:08 UTC | |
by Aristotle (Chancellor) on Aug 29, 2004 at 23:09 UTC |