6
votes

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"
}
1
You want the keys to be the elements of @one and the values the corresponding elements of @two? - Shawn
To use your approach, you could iterate over the index (of equal-length arrays) and add hash elements one at a time: for my $i (0..$#one) { $hash{$one[$i]} = $two[$i] }. But there are much better ways, like in @Shawn's answer. - zdim
Please always have use warnings; and use strict; at the beginning of programs. - zdim

1 Answers

13
votes

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;