我是Perl的新手,所以我遇到了一些麻烦。 假设我有两个数组:
@num = qw(one two three);
@alpha = qw(A B C);
@place = qw(first second third);
我想创建一个哈希,第一个元素作为键,剩余的值作为数组,无论它们是3还是3000个元素
因此散列基本上是这样的:
%hash=(
one => ['A', 'first'],
two => ['B', 'second'],
third => ['C', 'third'],
);
答案 0 :(得分:6)
use strict;
use warnings;
my @num = qw(one two three);
my @alpha = qw(A B C);
my @place = qw(first second third);
my %hash;
while (@num and @alpha and @place) {
$hash{shift @num} = [ shift @alpha, shift @place ];
}
use Data::Dump;
dd \%hash;
<强>输出强>
{ one => ["A", "first"], three => ["C", "third"], two => ["B", "second"] }
答案 1 :(得分:4)
use strict;
use warnings;
use Data::Dumper;
my %hash;
my @num = qw(one two three);
my @alpha = qw(A B C);
my @place = qw(first second third);
$hash{ $num[$_] } = [ $alpha[$_], $place[$_] ] for 0 .. $#num;
print Dumper \%hash
输出:
$VAR1 = {
'three' => [
'C',
'third'
],
'one' => [
'A',
'first'
],
'two' => [
'B',
'second'
]
};
答案 2 :(得分:3)
use strict;
use warnings;
use Algorithm::Loops 'MapCarE';
my @num = qw(one two three);
my @alpha = qw(A B C);
my @place = qw(first second third);
my %hash = MapCarE { shift, \@_ } \@num, \@alpha, \@place;
答案 3 :(得分:2)
use strict; use warnings;
my @num = qw(one two three);
my @alpha = qw(A B C);
my @place = qw(first second third);
my %h;
push @{ $h{$num[$_]} }, $alpha[$_], $place[$_] for 0..$#num;
use Data::Dumper;
print Dumper \%h;
$VAR1 = {
'three' => [
'C',
'third'
],
'one' => [
'A',
'first'
],
'two' => [
'B',
'second'
]
};
答案 4 :(得分:1)
use List::UtilsBy qw( zip_by );
my @num = qw(one two three);
my @alpha = qw(A B C);
my @place = qw(first second third);
my %hash = zip_by { shift, [ @_ ] } \@num, \@alpha, \@place;
输出:
$VAR1 = {
'three' => [
'C',
'third'
],
'one' => [
'A',
'first'
],
'two' => [
'B',
'second'
]
};