Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, I would like to know whether we can have multiple arrays as value in a hash for a unique key eg:
%number = { 23 =>[g1,23,24],[g2,34,35] 24 => [g3,45,56],[g4,36,48] }; $grp = number{23 }[0][0];
is it possible? if yes how can i push the new set of data to existing key and is it possible to populate such data structure directly from database? thnaks perlkid

Replies are listed 'Best First'.
Re: multiple array as hash value per key
by davorg (Chancellor) on Jul 02, 2009 at 05:51 UTC

    The values in a hash can be any kind of scalar. To get the results that you want, each value would need to be a reference to an array, and each element in the referenced arrays would need to be another array reference.

    %number = ( 23 => [ [ 'g1', 23, 24 ], [ 'g2', 34, 35 ] ], 24 => [ [ 'g3', 45, 56 ], [ 'g4', 36, 48 ] ], ); $grp = $number{23}[0][0];

    Note the I've corrected your hash-creating brackets from {} to ().

    For more details see perldsc.

    --

    See the Copyright notice on my home node.

    Perl training courses

      in case i have new set of data (new array) referring to same key,is it possible to push the array value to the hash? eg :
      new set is read from a file while ($line <>){ ($key,$value)=split(/,/,$line); #suppose #line have 23,['g8',23,45] push @{$numbers{23}},$value; }
      will this append the new array to existing key ?

        What you're looking for is probably more like:

        while (<>) { chomp; my ($key, @values) = split /,/, $_; push @{$numbers{$key}}, [ @values ]; }

        When playing with complex data structures, perldsc and Data::Dumper are your friend.

        --

        See the Copyright notice on my home node.

        Perl training courses

Re: mutiple array as hash value per key
by GrandFather (Saint) on Jul 02, 2009 at 05:53 UTC

    Close. A hash value is a scalar so you need a reference to an array. In fact you want a reference to an array of arrays so that looks like:

    use warnings; use strict; my %number = ( 23 => [['g1', 23, 24], ['g2', 34, 35]], 24 => [['g3', 45, 56], ['g4', 36, 48]], ); print "First group is: $number{23}[0][0]\n";

    Prints:

    First group is: g1

    Note the use of () (not {}) for the initialization list for the hash and that the group names need to be quoted.


    True laziness is hard work
Re: mutiple array as hash value per key
by bichonfrise74 (Vicar) on Jul 02, 2009 at 17:24 UTC
    Here you go...
    #!/usr/bin/perl use strict; use Data::Dumper; my %number = ( 23 => [ qq[g1,23,24], qq[g2,34,35] ], 24 => [ qq[g3,45,56], qq[g4,36,48] ] ); $number{25}->[0] = qq[g5,55,56]; print Dumper \%number;