Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl map - need to map an array into a hash as arrayelement->array_index

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?

like image 365
Paweł Hajdan Avatar asked Jun 02 '10 13:06

Paweł Hajdan


People also ask

How do I pass an array to a hash in Perl?

use strict; use Data::Dumper; my @array= qw(foo 42 bar); my %hash; @{ $hash{key} } = @array; $hash{key} = [ @array ]; #same as above line print Dumper(\%hash,$hash{key}[1]);

What does the map function do in Perl?

map() function in Perl evaluates the operator provided as a parameter for each element of List. For each iteration, $_ holds the value of the current element, which can also be assigned to allow the value of the element to be updated.

How do I define a map in Perl?

Working of map() function in Perl The symbol $_ holds the current element's value during each iteration of the list. The map() function can execute an expression on every element present in the array and return a new array consisting of resulting elements after the execution of the expression.

How do I create a hash reference in Perl?

Similar to the array, Perl hash can also be referenced by placing the '\' character in front of the hash. The general form of referencing a hash is shown below. %author = ( 'name' => "Harsha", 'designation' => "Manager" ); $hash_ref = \%author; This can be de-referenced to access the values as shown below.


2 Answers

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

print Dumper(\%hash)
$VAR1 = {
          'Field4' => 4,
          'Field2' => 2,
          'Field5' => 3,
          'Field1' => 1,
          'Field3' => 0
        };
like image 159
unbeli Avatar answered Oct 18 '22 04:10

unbeli


my %hash;
@hash{@arr} = 0..$#arr;
like image 30
Eugene Yarmash Avatar answered Oct 18 '22 04:10

Eugene Yarmash