I have looked over perl data type's and I have done a blanket Super Search for hashes, but I came up with nothing.

Here is the code:

use Data::Dumper; my %h; # intial hash # put in some random values $h{'a'}{'1'} = 'z'; $h{'a'}{'2'} = 'y'; $h{'a'}{'3'} = 'x'; $h{'b'}{'4'} = 'w'; $h{'b'}{'5'} = 'u'; $h{'b'}{'6'} = 'v'; $h{'c'}{'7'} = 'r'; $h{'c'}{'8'} = 's'; $h{'c'}{'9'} = 't'; # make an assignment that I assume is by value my %tmpHash = %h; # make a change in the temp hash $tmpHash{'b'}{'6'} = 'j'; print Dumper(%h); print "\n\n\n"; print Dumper(%x);
This ends up outputting:

$VAR1 = 'a';
$VAR2 = {
          1 => 'z',
          2 => 'y',
          3 => 'x'
        };
$VAR3 = 'b';
$VAR4 = {
          4 => 'w',
          5 => 'u',
          6 => 'j'
        };
$VAR5 = 'c';
$VAR6 = {
          8 => 's',
          9 => 't',
          7 => 'r'
        };



$VAR1 = 'a';
$VAR2 = {
          1 => 'z',
          2 => 'y',
          3 => 'x'
        };
$VAR3 = 'b';
$VAR4 = {
          4 => 'w',
          5 => 'u',
          6 => 'j'
        };
$VAR5 = 'c';
$VAR6 = {
          8 => 's',
          9 => 't',
          7 => 'r'
        };
As you can see, both hashes are changed. That surprised me. So, I am wondering how do you copy a hash by value. Is a foreach loop the only way to do it?

Jeremy

In reply to Assigning Hash To Another Hash References Same Hash by enoch

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.