Jay
Jay

Reputation: 751

Is there any way to create a hash with two arrays in perl?

I'm new to Perl, so I'm having a bit of trouble. Say I have two arrays:

@num = qw(one two three);
@alpha = qw(A B C);
@place = qw(first second third);

I want to create a hash with the first element as the key and the remaining as the values as an array, whether they have 3 or 3000 elements

So that the hash is essentially this:

%hash=(
    one => ['A', 'first'],
    two => ['B', 'second'],
    third => ['C', 'third'],
);

Upvotes: 1

Views: 200

Answers (5)

LeoNerd
LeoNerd

Reputation: 8542

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;

Output:

$VAR1 = {
      'three' => [
                   'C',
                   'third'
                 ],
      'one' => [
                 'A',
                 'first'
               ],
      'two' => [
                 'B',
                 'second'
               ]
    };

Upvotes: 1

Borodin
Borodin

Reputation: 126762

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;

output

{ one => ["A", "first"], three => ["C", "third"], two => ["B", "second"] }

Upvotes: 6

ysth
ysth

Reputation: 98423

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;

Upvotes: 3

Kenosis
Kenosis

Reputation: 6204

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

Output:

$VAR1 = {
          'three' => [
                       'C',
                       'third'
                     ],
          'one' => [
                     'A',
                     'first'
                   ],
          'two' => [
                     'B',
                     'second'
                   ]
        };

Upvotes: 4

Gilles Quénot
Gilles Quénot

Reputation: 185710

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;

Output

$VAR1 = {
          'three' => [
                       'C',
                       'third'
                     ],
          'one' => [
                     'A',
                     'first'
                   ],
          'two' => [
                     'B',
                     'second'
                   ]
        };

Upvotes: 2

Related Questions