develooper Front page | perl.perl5.porters | Postings from October 2003

Re: a strange $_ "mis"-behavior in map

Thread Previous | Thread Next
From:
Yitzchak Scott-Thoennes
Date:
October 9, 2003 00:39
Subject:
Re: a strange $_ "mis"-behavior in map
Message ID:
20031009073827.GA1776@efn.org
On Thu, Oct 09, 2003 at 12:29:30AM -0700, Stas Bekman <stas@stason.org> wrote:
> map {          "$_" => 1  } (a..c);
> 
> the first three lines are fine, the fourth produces an error:
> 
>   syntax error at /tmp/oops line 4, near "} ("
> 
> what's wrong with $_ stringification as the key? and it only happens 
> without () around the key/value pair.
> 
> Originally I planned to do:
> 
>  ... = map { "key_$_" => 1 } (a..c);
> 
> It seems to happen with all perls.

See perldoc -f map:

C<{> starts both hash references and blocks, so C<map { ...> could be either
the start of map BLOCK LIST or map EXPR, LIST. Because perl doesn't look
ahead for the closing C<}> it has to take a guess at which its dealing with
based what it finds just after the C<{>. Usually it gets it right, but if it
doesn't it won't realize something is wrong until it gets to the C<}> and
encounters the missing (or unexpected) comma. The syntax error will be
reported close to the C<}> but you'll need to change something near the C<{>
such as using a unary C<+> to give perl some help:

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

    %hash = map  ( lc($_), 1 ), @array  # evaluates to (1, @array)

or to force an anon hash constructor use C<+{>

   @hashes = map +{ lc($_), 1 }, @array # EXPR, so needs , at end

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About