Reputation: 959
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?
Upvotes: 16
Views: 21258
Reputation: 47
A very old question, but i had the same problem and this is my solution:
use feature ':5.10';
my @arr = ("Field3","Field1","Field2","Field5","Field4");
my %hash = map {state $i = 0; $_ => $i++} @arr;
Upvotes: 3
Reputation: 51316
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.
Upvotes: 2
Reputation: 150128
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;
}
Upvotes: 2
Reputation: 30248
%hash = map { $arr[$_] => $_ } 0..$#arr;
print Dumper(\%hash)
$VAR1 = {
'Field4' => 4,
'Field2' => 2,
'Field5' => 3,
'Field1' => 1,
'Field3' => 0
};
Upvotes: 26