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.

In reply to Re^3: Copy of multidimensional hash by muba
in thread Copy of multidimensional hash by tommaso.fornaciari

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.