Dear Perl Monks,
this is my first post, so sorry if I am wrong in some way.
I am working with multidimensional hashes, and I get an output which seems to me quite weird.
In particular:
- I create a multidimensional hash;
- I create a copy of this hash;
- I modify that copy.
When I print, it seems that both hashes were modified, and I do not understand why. With monodimensional hashes, everything is normal instead.
Please consider the following script and the output I receive:

#!/usr/bin/env perl use Modern::Perl 2011; use autodie; # I create a multidimensional hash my %one = ('a' => [1, 2], 'b' => [3, 4], 'c' => [5, 6]); # I create a copy: my %two = %one; # I print them: say "Before:\n\%one:"; for(sort keys %one){say "$_\t$one{$_}->[0]\t$one{$_}->[1]"} say '%two:'; for(sort keys %two){say "$_\t$two{$_}->[0]\t$two{$_}->[1]"} # Then I modify the copy: for(sort keys %two){$two{$_}->[1] = 'two'} # And I print again: say "After:\n\%one:"; for(sort keys %one){say "$_\t$one{$_}->[0]\t$one{$_}->[1]\tWhy???"} say '%two:'; for(sort keys %two){say "$_\t$two{$_}->[0]\t$two{$_}->[1]"} # I receive this output: #Before: #%one: #a 1 2 #b 3 4 #c 5 6 #%two: #a 1 2 #b 3 4 #c 5 6 #After: #%one: #a 1 two Why??? #b 3 two Why??? #c 5 two Why??? #%two: #a 1 two #b 3 two #c 5 two

Thanks for any explanation you could give me!
Tommaso


In reply to 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.