Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re^2: Making a hash of arrays from a while loop

by why_bird (Pilgrim)
on Mar 04, 2008 at 09:40 UTC ( #671832=note: print w/replies, xml ) Need Help??


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' ] };

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://671832]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (2)
As of 2023-06-03 03:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    How often do you go to conferences?






    Results (6 votes). Check out past polls.

    Notices?