« Quick notes when hacking for compile time | Home | PerlX - Perl Extension »
August 28, 2009
Funny about the minus sign
I just discovered that there something funny about this minus sign. See if you can guess the output of the following code without running it:
use strict;
use 5.010;
$, = " ";
for my $v (qw(42 FortyTwo)) {
say -$v, -"$v", -("$v");
say -(-($v)) , -(-$v), -(-$v);
say -(-("$v")) , -(-"$v"), -(-$v);
say -(-(-("$v"))) , -(-(-"$v")) , -(-(-$v));
}
It’s pretty easy when the $v is 42, but not quite obvious when it is "FortyTwo". I don’t have any explain on it. That’s maybe documented somewhere and I’ll have to find it.
No TrackBacks
TrackBack URL: http://gugod.org/mt/mt-tb.cgi/240
In the same vein of surprising behavior:
Interesting. I'm not sure how or where, but I'm sure there's a use for that quirk to be found. :-)
It's documented in perldoc perlop ("Symbolic Unary Operator"):
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.