Perl map - need to map an array into a hash as arr

2020-02-17 09:58发布

问题:

I have a array like this:

my @arr = ("Field3","Field1","Field2","Field5","Field4");

Now i use map like below , where /DOSOMETHING/ is the answer am seeking.

my %hash = map {$_ => **/DOSOMETHING/** } @arr

Now I require the hash to look like below:

Field3 => 0
Field1 => 1
Field2 => 2
Field5 => 3
Field4 => 4

Any help?

回答1:

%hash = map { $arr[$_] => $_ } 0..$#arr;

print Dumper(\%hash)
$VAR1 = {
          'Field4' => 4,
          'Field2' => 2,
          'Field5' => 3,
          'Field1' => 1,
          'Field3' => 0
        };


回答2:

my %hash;
@hash{@arr} = 0..$#arr;


回答3:

Here's one more way I can think of to accomplish this:

sub get_bumper {
    my $i = 0;
    sub { $i++ };
}

my $bump = get_bumper;         # $bump is a closure with its very own counter
map { $_ => $bump->(); } @arr;

As with many things that you can do in Perl: Don't do this. :) If the sequence of values you need to assign is more complex (e.g. 0, 1, 4, 9, 16... or a sequence of random numbers, or numbers read from a pipe), it's easy to adapt this approach to it, but it's generally even easier to just use unbeli's approach. The only advantage of this method is that it gives you a nice clean way to provide and consume arbitrary lazy sequences of numbers: a function that needs a caller-specified sequence of numbers can just take a coderef as a parameter, and call it repeatedly to get the numbers.



回答4:

In Perl 5.12 and later you can use each on an array to iterate over its index/value pairs:

use 5.012;

my %hash;

while(my ($index, $value) = each @arr) {
    $hash{$value} = $index;
}