user2377038
user2377038

Reputation: 21

How to add an array of an array to values of hash?

I have an array a1 and an array-of-arrays a2.

@a1 = [1,2,3,4,5] 

and

@a2 = [ [adf],[bcg],[yet],[gpd],[iop]]

I want to have a hash where a1 are the keys and arrays of a2 as values. How do I do it?

Upvotes: 0

Views: 49

Answers (2)

raul
raul

Reputation: 109

my @keys = (1,2,3,4,5);
my @vals = ( ["a", "d", "f"], ["b", "c", "g"], ["y","e","t"], 
           ["g", "p", "d"], ["i", "o", "p"] );

my $hash={};

for(my $i = 0; $i < scalar(@keys); $i++){

    $hash->{$keys[$i]}=$vals[$i];
}

#print the resulted hash
use Data::Dumper;print Dumper($hash);

Result looks like: $VAR1 = { '4' => [ 'g', 'p', 'd' ], '1' => [ 'a', 'd', 'f' ], '3' => [ 'y', 'e', 't' ], '2' => [ 'b', 'c', 'g' ], '5' => [ 'i', 'o', 'p' ] };

Perl hashes are unordered so don't worry about the order in which they are printed here, you could sort them based on the numeric keys if necessary.

Upvotes: 1

dms
dms

Reputation: 817

Here are a couple of ways to do it. Your syntax is a bit off in your question so I'm going to assume my variable declarations are what you wanted.

my @a1 = (1,2,3,4,5);
my @a2 = ( ["a", "d", "f"], ["b", "c", "g"], ["y","e","t"], 
           ["g", "p", "d"], ["i", "o", "p"] );
# Thus $a2[0][1] => "d", etc.                                                                                                                                           

#Perl 5.12 and higher you can use "each" on an array
my %a3;
while (my ($a1_index, $a1_value) = each @a1) {
    $a3{$a1_value} = $a2[$a1_index];
}
# Now @{$a3{4}} => ["g", "p", "d"] for example

# Before 5.12 you would have to do something like this:
my %a4;
for my $i (0..$#a1) {
    $a4{$a1[$i]} = $a2[$i];
}
# Now @{$a4{4}} => ["g", "p", "d"]

Upvotes: 1

Related Questions