in reply to Re: Re: Confused about unary +
in thread Confused about unary +
I think the point is that this use of unary + to disambiguate various forms of syntax is:
I'm reasonably sure you won't find any other language that overloads a mathematical symbol for a purely syntactic purpose this way. Unary + or any other.
The ambiguities in the Perl syntax that lead to the requirement to disambiguate them in this way simply don't arise in most other languages. Either the parens are required, or spaces are significant and therefore serve (and can be relied upon) to prevent the ambiguity from arising.
Essentially, any token could have been used to serve this purpose. Unary + just happened to be convenient.
My best guess as to why unary + was chosen to fullfil this extra-semantic role is that, in most places where you can legitimately use unary +, in its mathematical and/or semantic role, it has exactly zero effect.
Eg. $x=-1; print + -1; # print '-1'.
We could always write positive numbers starting with +, for( my $i=+0; $i< +100; $i += +1){ .. };. We don't because, in most if not all cases, it has exactly zero effect.
However, it does have an effect at the level of the parser. When the parser encounters a +, especially one that was not preceeded by an expression or term, then the parser know what follows must be an expression or term and not a list.
So, my guess is that seeing as the parser has to deal with this mathematically valid, but otherwise semantically useless syntax -- any expression or term can legally preceeded by unary + -- then using it to disambigute those situations where an expression might be mistaken for a list added little or no overhead to the parser, but saved inventing a token for this purpose--which perl suffers from a distinct glut of anyway:)--and also allowed Perl's "whitespace is insignificant", free-form syntax to remain without requiring a special case that might otherwise have been required.
Reading that back, I'm not at all sure that this explanation is any clearer than those that preceed it, or even that it is completely correct, but it made sense as I typed it:)
Just to add another one to your list
@_ = 'world!'; my %hash; $hash{ shift } = 'Hello'; $hash{ +shift } = 'Goodbye'; print "$k => $v\n" while my($k, $v) = each %hash; # prints shift => 'Hello' world! => 'Goodbye'
In this case using shift() instead of +shift would have served to force the compiler to treat shift as an term (and therefore a function as there is no sigil) rather than as a (splendid) bareword string as in the first line above.
|
|---|