Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Making a hash of arrays from a while loop

by moritz (Cardinal)
on Mar 04, 2008 at 09:30 UTC ( #671829=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (1)
As of 2023-09-23 18:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?