in reply to Making a hash of arrays from a while loop

Storing @array in a hash %hash with $key as the key is a simple matter of one line:
$hash{$key} = \@array;

Replies are listed 'Best First'.
Re^2: Making a hash of arrays from a while loop
by why_bird (Pilgrim) on Mar 04, 2008 at 09:40 UTC
    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
    .......
      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
        .......
      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' ] };