Reputation: 751
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
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
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
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
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
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;
$VAR1 = {
'three' => [
'C',
'third'
],
'one' => [
'A',
'first'
],
'two' => [
'B',
'second'
]
};
Upvotes: 2