Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re^2: strange syntax error with map (unary plus)

by LanX (Saint)
on Apr 09, 2017 at 13:52 UTC ( [id://1187524]=note: print w/replies, xml ) Need Help??


in reply to Re: strange syntax error with map
in thread strange syntax error with map

>   perl -wMstrict -le 'print map { +2, $_ } 1 .. 2'

I'm not a big fan of the unary plus solution, since it's not easily understandable why the unary plus sometimes works or not.

Fun with Perl's parsing:

DB<100> map {+2,$_} 1..3 # +2 is not a hash key => (2, 1, 2, 2, 2, 3) DB<101> map {2,$_} 1..3 # 2 is a hash key ;; Not enough arguments for map at (eval 21)[multi_perl5db.pl:644] line 2, near "} 1" syntax error at (eval 21)[multi_perl5db.pl:644] line 2, near "} 1" DB<102> map {2,$_}, 1..3 # 2 is a hash key => ({ 2 => 1 }, { 2 => 2 }, { 2 => 3 }) DB<103> map {+2,$_}, 1..3 # +2 is not a hash key ;; syntax error at (eval 26)[multi_perl5db.pl:644] line 2, near "}," DB<104> map {+2 => $_}, 1..3 # +2 is not a hash key even with fat co +mma ;; syntax error at (eval 29)[multi_perl5db.pl:644] line 2, near "},"

so far so consistent, BUT

DB<105> map +{+2 => $_}, 1..3 # +2 IS A HASH KEY => ({ 2 => 1 }, { 2 => 2 }, { 2 => 3 }) DB<106> map +{+2 , $_}, 1..3 # +2 IS A HASH KEY even without => => ({ 2 => 1 }, { 2 => 2 }, { 2 => 3 })

see my point? :)

Cheers Rolf
(addicted to the Perl Programming Language and ☆☆☆☆ :)
Je suis Charlie!

Replies are listed 'Best First'.
Re^3: strange syntax error with map (unary plus)
by haukex (Archbishop) on Apr 09, 2017 at 17:48 UTC
    I'm not a big fan of the unary plus solution

    I agree, I was just keeping the examples in line with what the map docs were saying. Personally in this case I'd prefer map { (...) } ..., since it makes it look obvious that returning a list is intentional. OTOH I also use map {$_=>1} ... very often, but that one doesn't cause any parse trouble.

    The map +{...}, ... stuff is also mentioned in the map docs, although I haven't yet seen it used in the wild - personally I'd probably write map { {...} } .... As you can tell I usually prefer map BLOCK LIST over map EXPR, LIST.

    ... to force an anon hash constructor use +{:
    my @hashes = map +{ lc($_) => 1 }, @array # EXPR, so needs # comma at end
    to get a list of anonymous hashes each with only one entry apiece.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1187524]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (3)
As of 2024-04-26 03:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found