Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re^3: Copy of multidimensional hash

by muba (Priest)
on Jan 03, 2013 at 10:38 UTC ( #1011436=note: print w/ replies, xml ) Need Help??


in reply to Re^2: Copy of multidimensional hash
in thread Copy of multidimensional hash

Is this the best way to create a copy of a multidimensional hash?

I don't know if it's the best. At any rate, I would reformat the for loop as follows:

for (keys %one) { $two{$_}[0] = $one{$_}[0]; $two{$_}[1] = $one{$_}[1]; }

I find this significantly more readable than the way you formatted it. Furthermore, I would generalize copying the arrray, and tell Perl to take out all the elements instead of just those elements with index 0 and 1.

for my $k (keys %one) { $two{$k}[$_] = $one{$k}[$_] for 0..scalar( @{$one{$k}} ); }

And then I would generalize it even further: take the whole array reference, dereference it in a single pass, and create and store a new reference to it. Sounds complex? Nah, not so much:

for my $k (keys %one) { $two{$k} = [ @{$one{$k}} ]; }

This was already suggested by johngg.</p

Step by step of [ @{$one{$k}} ]:

  1. $one{$k}: this takes the element identified by key $k from hash %one. That element, in this case, is an array reference.
  2. @{ ... } dereferences the array reference inside the curlies. So after @{ $one{$k} } we're working with a normal, regular, every day array (albeit an anonymous one).
  3. [ ... ] stores whatever is between the square braces as an anonymous array and returns a reference to it.

But then I would want to generalize it even further and use Storable's dclone function, as suggested by davido.

use Storable qw(dclone); ... my %two = %{ dclone(\%one) } # dclone() takes a ref and returns a r +ef # So we'll have to put in \%one (not % +one) # and then we have to dereference ( %{ +...} ) # what comes out.


Comment on Re^3: Copy of multidimensional hash
Select or Download Code
Re^4: Copy of multidimensional hash
by tommaso.fornaciari (Initiate) on Jan 03, 2013 at 11:24 UTC

    Thanks muba, thanks johnGG,
    great dissertation about the the topic :))

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (9)
As of 2014-10-23 17:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (126 votes), past polls