Thread Block vs. Hashref (25 answers)
Opened by barney at 2024-08-02 13:17

GwenDragon
 2024-08-02 17:43
#196618 #196618
User since
2005-01-17
14760 Artikel
Admin1
[Homepage]
user image
Laut Perldoc map
https://perldoc.pl/functions/map
{ starts both hash references and blocks, so map { ... could be either the start of map BLOCK LIST or map EXPR, LIST. Because Perl doesn't look ahead for the closing } it has to take a guess at which it's dealing with based on what it finds just after the {. Usually it gets it right, but if it doesn't it won't realize something is wrong until it gets to the } and encounters the missing (or unexpected) comma. The syntax error will be reported close to the }, but you'll need to change something near the { such as using a unary + or semicolon to give Perl some help:

my %hash = map { "\L$_" => 1 } @array # perl guesses EXPR. wrong
my %hash = map { +"\L$_" => 1 } @array # perl guesses BLOCK. right
my %hash = map {; "\L$_" => 1 } @array # this also works
my %hash = map { ("\L$_" => 1) } @array # as does this
my %hash = map { lc($_) => 1 } @array # and this.
my %hash = map +( lc($_) => 1 ), @array # this is EXPR and works!

my %hash = map ( lc($_), 1 ), @array # evaluates to (1, @array)
or 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.

Last edited: 2024-08-02 17:44:21 +0200 (CEST)

View full thread Block vs. Hashref