views:

147

answers:

4

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.

+2  A: 

If I understand the problem correctly:

my %c;
$c{$a[$_]} = $b[$_] for (0 .. @a-1);
Hans W
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
@Boldewyn: usually fixed by using real variable names
ysth
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
+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
Nice one, I hadn't thought about using map.
Hans W
ysth
+21  A: 

it's as simple as

my %c;
@c{@a} = @b;
newacct
Great! I forgot about the slice solution, though I use it regularly.
codeholic
Thanks! I wonder why it is not in the books (ones I read).
http://perldoc.perl.org/perldata.html#Slices
toolic
You're probably reading the wrong books. _Learning Perl_ shows this in the slice section. :)
brian d foy