i would like to understand why the '+' notation does not work as expected

unary-+ literally has no effect. It does nothing. It just returns the value provided to it.

It's even transparent to context

$ perl -Mv5.14 -e'my @a = qw( d e f ); say for +@a' d e f

So why do we use it?

Well, the Perl grammar has ambiguities. The same sequence of tokens could have two valid meanings. So Perl sometimes has to guess which meaning you mean. By inserting the do-nothing unary-+ in that sequence, we can sometimes create a sequence that's no longer ambiguous, or one that changes how Perl chooses to resolve the ambiguity.

For example, the { in map { could be the start of a block or it could be the start of a hash constructor. This is an ambiguity. However, the { in map +{ can only be the start of a hash constructor. There is no ambiguity.

So what about $hash{ +FOO }?

$hash{ FOO } is ambiguous, except it's documented that Perl will auto-quote what's in the curlies if it's entirely an identifier. Therefore, this is treated as $hash{ "FOO" }.

$hash{ +FOO } avoids that. Since the entirety of the contents of the curlies is no longer entirely an identifier, it's not auto-quoted, letting FOO have the same meaning it would have in my $key = FOO;.

So what about +FOO => ...?

=> auto-quotes the identifier that precedes it, if any. With or without the +, FOO is still right before the => and thus gets treated as "FOO".


In reply to Re: Why is +CONST left to a fat comma not treated as in $hash{+CONST}? by ikegami
in thread Why is +CONST left to a fat comma not treated as in $hash{+CONST}? by Darkwing

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.