Home > Software design >  How do I copy list elements to hash keys in perl?
How do I copy list elements to hash keys in perl?

Time:05-29

I have found a couple of ways to copy the elements of a list to the keys of a hash, but could somebody please explain how this works?

use v5.34.0;

my @arry = qw( ray bill lois shirly missy hank );

my %hash;
$hash{$_}   for @arry;  # What is happening here?

foreach (keys %hash) {
  say "$_ => " . $hash{$_};
}
                                                                                                                                         

The output is what I expected. I don't know how the assignment is being made.
hank => 1
shirly => 1
missy => 1
bill => 1
lois => 1
ray => 1

CodePudding user response:

$hash{$_} for @arry; # What is happening here?

It is iterating over the array, and for each element, it's assigning it as a key to the hash, and incrementing the value of that key by one. You could also write it like this:

my %hash;
my @array = (1, 2, 2, 3);

for my $element (@array) {
    $hash{$element}  ;
}

The result would be:

$VAR1 = {
          '2' => 2,
          '1' => 1,
          '3' => 1
        };

CodePudding user response:

Here is a short one

my %hash = map { $_ => 1 } @ary;

Explanation: map takes an element of the input array at a time, and for each prepapres a list of two, the element itself ($_, also quoted because of =>) and a 1. Any list of an even length can be assigned to a hash, whereby each two successive elements form a key-value pair, and here we form those pairs as neede.

CodePudding user response:

$hash{$_}   for @arry;  # What is happening here?

Read perlsyn, specifically simple statements and statement modifiers:

Simple Statements

The only kind of simple statement is an expression evaluated for its side-effects. Every simple statement must be terminated with a semicolon, unless it is the final statement in a block, in which case the semicolon is optional. But put the semicolon in anyway if the block takes up more than one line, because you may eventually add another line. Note that there are operators like eval {}, sub {}, and do {} that look like compound statements, but aren't--they're just TERMs in an expression--and thus need an explicit termination when used as the last item in a statement.

Statement Modifiers

Any simple statement may optionally be followed by a SINGLE modifier, just before the terminating semicolon (or block ending). The possible modifiers are:

if EXPR
unless EXPR
while EXPR
until EXPR
for LIST
foreach LIST
when EXPR

[...]

The for(each) modifier is an iterator: it executes the statement once for each item in the LIST (with $_ aliased to each item in turn). There is no syntax to specify a C-style for loop or a lexically scoped iteration variable in this form.

print "Hello $_!\n" for qw(world Dolly nurse);
  • Related