1

私はPerlを初めて使用するので、少し問題があります。2 つの配列があるとします。

@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 に答える