How to "match" the interpretation of its first argument in Perl?

I have some questions about the Perl "map" function.

In particular:

  • how

    % hash = map {$ _ => 1} @array

    to create hash mapping array elements for 1? How does a block return a list of two elements? I thought the block was returning its last value. Does => implicitly create a list, as opposed to a "," that returns its correct argument?

  • Why

    % hash = map ($ _ => 1), @array

    does not work? I am trying to return a list of two elements here ... And how to add a "+" to "(" fix it, from the point of view of the parser?

+5
source share
4 answers

1: , , , . map . "," "=>" , . . perlop.

2: %hash = map ($_ => 1), @array %hash = (map($_, 1), @array). , (1, @array). %hash = map +($_ => 1), @array + , () , map (+ ($ _ = > 1), @array);

: , , .

+9

@Leon , :

from perlop

"+" , .          ,      .

deparse, , perl :

perl -MO=Deparse,-p -e "%h = map ($_ => 1), @a;"
(((%h) = map($_, 1)), @a);

as

perl -MO=Deparse,-p -e "%h = map +($_ => 1), @a;"
((%h) = map(($_, 1), @a));

,

+4

- . {}. , , .

: , + 1 . , - ? perldoc.

0

The map applies a block to each value in the array / list and creates a new list. => is syntactic sugar to show that the list consists of key / value pairs (IIRC, it will work with a regular comma). When you assign a list of alternatig key / value pairs to a hash variable, a hash table is created.

Another option does not work, because it is not a code block. I do not know about +.

0
source

All Articles