Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

help reassigning hash with arrayref

by mhearse (Hermit)
on Nov 15, 2011 at 22:42 UTC ( #938271=perlquestion: print w/ replies, xml ) Need Help??
mhearse has asked for the wisdom of the Perl Monks concerning the following question:

I have a hash (%tmp) which looks like so:
$VAR1 = { 'one' => [ '1234', '5678', ], 'two' => [ '91011', '121314', ], 'three' => [ '151617', '181920', '212223', ] };
I'm trying to reassign it like this, but it must be broken:
my %hash; for my $key (keys %tmp) { $hash{$key} = { $key => @{$tmp{$key}} }; }

Comment on help reassigning hash with arrayref
Select or Download Code
Re: help reassigning hash with arrayref
by GrandFather (Cardinal) on Nov 15, 2011 at 22:59 UTC

    It's not clear what you want to achieve, but most likely you want a deep copy like this:

    for my $key (keys %tmp) { $hash{$key} = [@{$tmp{$key}}]; }
    True laziness is hard work
      I want to end up with:
      $hash{one} = { $key => $tmp{$key} };
      But for some reason the array is being assigned in scalar context.

        No, that is not what you want to end up with. You may think that is what you need to do to end up with whatever it is that you want, but it's the (presumably non-working) means to an end. It would help a lot if you showed us the structure you want to end up with. What do you want to see in %hash?

        True laziness is hard work
Re: help reassigning hash with arrayref
by johnny_carlos (Scribe) on Nov 15, 2011 at 23:00 UTC
    Are you going to do something with the values, because it looks like you are just copying the hash.. The simple way to do a re-assignment would just be: my %hash = %tmp;

      Note though that that provides references to the arrays in the original hash so any changes to those arrays will be seen by the arrays in the new hash. That might or might not be what the OP wants, but probably isn't.

      True laziness is hard work

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://938271]
Approved by GrandFather
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (8)
As of 2014-09-01 14:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite cookbook is:










    Results (13 votes), past polls