Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a Perl hash from an array with the keys and another array with the values?

Tags:

arrays

hash

perl

In Perl, how do I make hash from arrays @A and @B having equal number of elements? The goal is to have each value of @A as key to value in @B. The resulting hash %C would,then make it possible to uniquely identify an element from @B supplying key from @A.

like image 739
Temujin Avatar asked Feb 21 '10 17:02

Temujin


2 Answers

it's as simple as

my %c;
@c{@a} = @b;
like image 188
newacct Avatar answered Sep 28 '22 20:09

newacct


use List::MoreUtils 'mesh';
my %c = mesh @a, @b;

That's how it's made internally (if you're sure about equal number of elements):

my %c = map { $a[$_] => $b[$_] } 0 .. $#a;
like image 44
codeholic Avatar answered Sep 28 '22 19:09

codeholic