Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I map two arrays into one Perl hash?

Tags:

perl

I am new to perl. I need to understand how can I map one array (as keys) to another (as values) to result in a hash using foreach loop:

@one = ("A", "B", "C");
@two = ("a", "b", "c");

I wrote the following code but it does not work when I slice the hash??

%hash;
foreach $i (one) {
  print $i, "=>" , $ii = shift @two, "\n"
}
like image 995
Sayed Sabry Avatar asked Sep 10 '18 00:09

Sayed Sabry


People also ask

How do I merge two arrays into a hash in Perl?

You can do it in a single assignment: my %hash; @hash{@array1} = @array2; It's a common idiom.

How do I create an array of hashes in Perl?

To add another hash to an array, we first initialize the array with our data. Then, we use push to push the new hash to the array. The new hash should have all of its data. As shown below, you can see the difference between the two arrays before and after pushing a new hash.

How do I append a hash in Perl?

@values = @{ $hash{"a key"} }; To append a new value to the array of values associated with a particular key, use push : push @{ $hash{"a key"} }, $value; The classic application of these data structures is inverting a hash that has many keys with the same associated value.

What is map 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.


1 Answers

Assuming the answer to my question in the comment is "yes", here's a couple of approaches.

Given:

my @one = qw/A B C/;
my @two = qw/1 2 3/;

Using hash slices:

my %hash;
@hash{@one} = @two;

Using the List::MoreUtils module from CPAN:

use List::MoreUtils qw/zip/;
my %hash = zip @one, @two;
like image 82
Shawn Avatar answered Sep 28 '22 06:09

Shawn