问题
I have 2 arrays of the following form:
root rhino root root root root root root root root root root domainte root
stam rhino jam onetwo domante ftpsi jay testwp contra raul vnod foos raul bruce
Notice that they are of equal length (and always will be). I want to create a hash such that there is one single key called root whose values are the corresponding values from the second array. Basically, the elements of the first array need to be the keys and the elements from the second array need to be the values, but keys need to be unique and values could be an array.
How do I go about achieving this result? Sorry, quite new to to Perl.
回答1:
Just iterate over the indexes of both the arrays, pushing each value to the corresponding array reference at the key.
#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;
my @keys = qw(root rhino root root root root root root root root root root domainte root);
my @values = qw(stam rhino jam onetwo domante ftpsi jay testwp contra raul vnod foos raul bruce);
my %hash;
for my $idx (0 .. $#keys) {
push @{ $hash{ $keys[$idx] } }, $values[$idx];
}
print Dumper \%hash;
回答2:
Choroba's solution is perfect, but I like to use map for things like this.
#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;
my $i=0;
my %hash;
map {push @{$hash{$_}}, $values[$i++]} @keys;
print Dumper \%hash;
I used Time::HiRes to check the run time for each of these and the map method is 15/10000 of a second faster than the loop method (insignificant in a small run, but might add up over thousands or millions of cycles).
来源:https://stackoverflow.com/questions/19544309/perl-creating-a-hash-from-two-arrays