1

我是 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'],
);
4

5 回答 5

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"] }
于 2013-02-27T02:39:24.293 回答
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'
                   ]
        };
于 2013-02-27T02:45:19.437 回答
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;
于 2013-02-27T03:59:24.240 回答
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'
                   ]
        };
于 2013-02-27T02:42:38.113 回答
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'
               ]
    };
于 2013-03-01T16:42:48.300 回答