http://qs1969.pair.com?node_id=671832


in reply to Re: Making a hash of arrays from a while loop
in thread Making a hash of arrays from a while loop

Yes, but it doesn't store the values, (as far as I can tell---otherwise I'll post my code and see what else stupid I am doing wrong!) it stores a reference to the array, so when the array is recalculated, doesn't the reference point to the new value of the array?
........
Those are my principles. If you don't like them I have others.
-- Groucho Marx
.......
  • Comment on Re^2: Making a hash of arrays from a while loop

Replies are listed 'Best First'.
Re^3: Making a hash of arrays from a while loop
by moritz (Cardinal) on Mar 04, 2008 at 09:42 UTC
    You're right, and the workaround is to create a new array:
    $hash{$key} = [ @array ];

    If there are references inside the array, you'll need somthing like Storable::dclone.

      Ahh, that's what I was trying to do---I couldn't figure out how to make an anonymous array like that. Thankyou v much!
      ........
      Those are my principles. If you don't like them I have others.
      -- Groucho Marx
      .......
Re^3: Making a hash of arrays from a while loop
by wfsp (Abbot) on Mar 04, 2008 at 12:40 UTC
    Or declare @array within the while loop. This avoids making a copy of the array to make the anonymous reference.
    #!/usr/bin/perl use strict; use warnings; use Data::Dumper; $Data::Dumper::Indent = 1; my %hash; while (my $rec = <DATA>){ chomp $rec; # declare the array my ($key, @array) = split(/ /, $rec, 2); $hash{$key} = \@array; } print Dumper \%hash; __DATA__ 1 2 3 4 5 6 7 8
    $VAR1 = { '1' => [ '2 3 4' ], '5' => [ '6 7 8' ] };