Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a hash in which the key is an array, and the value is an array of arrays

I'm trying to create a hash in which keys are contained in an array and values in an array of an array:

my @keys = (1,2,3,4,5);
my @value1 = (a,b,c,d,e);
my @value2 = (f,g,h,i,j);
my @value3 = (k,l,m,n,o);

my @values = ([@value1],[@value2],[@value3]);

my %hash;

I want to create a hash with @keys as keys, and @values as values so that key '1' would return the values a,f,k (0th element in each array) and so on.

For a single key this would be achieved as follows:

%hash=('key'=>@values);

But I'm unsure how to modify this for an array of keys.

Any help would be amazing!

Cheers,

N

like image 874
fugu Avatar asked Jan 14 '23 07:01

fugu


2 Answers

Something like this:

my %hash = map { $keys[$_] => [ $value1[$_], $value2[$_], $value3[$_] ] } 0..$#keys;

assuming that all four lists have the same length.

like image 176
Vedran Šego Avatar answered Jan 30 '23 23:01

Vedran Šego


I take advantage of the syntax $foo[$i][$j]; to represent your array of arrays as a two dimensional array. Here's an answer sans the map:

#! /usr/bin/env perl

use 5.12.0;
use warnings;
use Data::Dumper;

my @keys = qw(alpha beta gamma delta epsolon);

my @values1 = qw(one two three four five);
my @values2 = qw(uno dos tres quatro cinco);
my @values3 = qw(a b c d e);

my @values = ( \@values1, \@values2, \@values3 );

my %hash;
for my $item ( (0..$#keys) ) {
    my @array;
    push @array, $values[0][$item], $values[1][$item], $values[2][$item];
    $hash{$keys[$item]} = \@array;
}

say Dumper \%hash;

Here's the output:

$VAR1 = {
      'gamma' => [
           'three',
           'tres',
           'c'
         ],
      'delta' => [
           'four',
           'quatro',
           'd'
         ],
      'alpha' => [
           'one',
           'uno',
           'a'
         ],
      'beta' => [
          'two',
          'dos',
          'b'
        ],
      'epsolon' => [
             'five',
             'cinco',
             'e'
           ]
    };

Looks about right. Of course, I never verified that the various arrays are all the same size.

like image 30
David W. Avatar answered Jan 30 '23 23:01

David W.