Search code examples
arraysperlhashtable

How to parse an array to a hash of arrays?


I'm a beginner (a wet lab biologist, who has to fiddle a bit with bioinformatics for the first time in my life) and today I've got stuck on one problem: how to parse an array to a hash of arrays in perl?

This doesn't work:

@myhash{$key} = @mytable;

I've finally circumvented my problem with a for loop:

for(my $i=0;$i<=$#mytable;$i++){$myhash{$key}[$i]=$mytable[$i]};

Of course it works and it does what I need to be done, but it seems to me not a solution to my problem, but just a way to circumvent it... When something doesn't work I like to understand why...

Thank you very much for your advice!


Solution

  • As Grinnz mentioned you can save a reference to an array, but any change on the array latter will be reflected in hash (it is same data).

    For example if you reuse same array in the loop then data in hash will reflect last iteration of the loop.

    In such case you will want a copy of array stored in the hash.

    @{$hash{$key}} = @array;
    

    Programming Perl: Data strutures