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
.
views:
147answers:
4
+2
A:
If I understand the problem correctly:
my %c;
$c{$a[$_]} = $b[$_] for (0 .. @a-1);
Hans W
2010-02-21 17:32:59
I really like Perl, but sometimes one can despair on a programming language allowing you for more non-letter chars than letters in your source code...
Boldewyn
2010-02-21 18:24:07
@Boldewyn: usually fixed by using real variable names
ysth
2010-02-21 23:28:57
A:
A's are the keys, B's are the values of hash C:
use strict;
use warnings;
my @a = 1 .. 3;
my @b = 4 .. 6;
my %c;
for (0 .. $#a) {
$c{$a[$_]} = $b[$_]
}
Keep in mind that there must not be any duplicate values in the A array.
toolic
2010-02-21 17:34:07
+8
A:
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;
codeholic
2010-02-21 17:37:56
You're probably reading the wrong books. _Learning Perl_ shows this in the slice section. :)
brian d foy
2010-02-21 23:29:07