I'm not positive about this...

I'm not positive about this, but I'm not sure that things are behaving as I would expect. What would you expect the following lines to output?

perl -E 'say "x"; say -"x"; say -"-x"; say -"+x";'

For me, lines 1 and 2 make sense. Lines 3 and 4 are different than I would expect, but I'm not sure that they are really wrong. Does somebody want to explain what is really happening, and why it is that way?


This is because the unary minus operator is weird. If it's applied to a string that starts with a plus or minus, which isn't a number, it reverses that sign; if it doesn't start with a plus or minus, it adds a minus. It even does this in a strict-safe way with barewords, which is how the popular "use Foo -bar" syntax works in strict mode, and also how this more interesting code is strict safe: "say - -foo". The full details are listed in perldoc perlop "Symbolic Unary Operators".

Personally, I think 1 (obviously) makes sense; the rest are weird Perl unary-minus behaviors. Remember that Perl (unlike shell or C) does not let you concatenate strings by putting them next to each other; instead you have to use . (dot): say "-"."x". (Indeed, say a"x" produces no output — confusing unless you turn on warnings).

And something like say 1+"x" prints 1; Perl turns the string to a 0 (and prints a warning if enabled) — in every math operator but unary +/-. Perl doesn't do algebra.

So I find it weird (but documented, and useful) that 2, 3, and 4 don't all print 0.

Leave a comment

About $Bob

user-pic I blog about Perl.