Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

Re: hash ref mind blow

by duckyd (Hermit)
on Sep 24, 2008 at 16:27 UTC ( [id://713464] : note . print w/replies, xml ) Need Help??

in reply to hash ref mind blow

The following might help to make things a little more clear. Hash has 2 values, which are both hash references (to a anonymous hashes { drinks => 1 } and { drinks => 2 }). When you do the shallow copy, the hash references are copied, but they still refer to the same hashes in both %hash and %copy:
use strict; my %hash = (); $hash{a}{drinks}=1; $hash{b}{drinks}=2; my $p = \%hash; my %copy = %{ $p }; print "ref hash: ", \%hash, "\nref copy: ", \%copy, "\n"; print "values hash: ",join(", ", values %hash), "\nvalues copy: ",join +(", ", values %copy), "\n";
copy: ab hash: ab ref hash: HASH(0x82ef7d8) ref copy: HASH(0x82ef928) values hash: HASH(0x82e0308), HASH(0x82ef788) values copy: HASH(0x82e0308), HASH(0x82ef788)
Note that the values are identical, and thus the values of %hash and %copy refer to the same hash references.

Replies are listed 'Best First'.
Re^2: hash ref mind blow
by Anonymous Monk on Sep 24, 2008 at 16:51 UTC
    Yup, perfectly clear! Thank you! But I've just realized that I don't how to do one thing... how can I make %hash and %copy be in the same mem location? So that when I add a new key to %copy, %hash also changes. I'm just lazy about working with a ref directly as in
    I just want
    To change the value of %hash.

      For global variables, just do a glob assignment:

      *copy = \%hash;

      then, %copy and %hash are the same data structure. Otherwise, that is, for lexical variables, use Data::Alias.

        Make sure to localize package variables (such as *copy).

        our %copy; local *copy = \%hash;


        use Data::Alias; alias my %alias = %hash;
      Just so you know, Data::Dumper is part of every perl
      #!/usr/bin/perl -- use strict; my %hash = (); $hash{a}{drinks}=1; $hash{b}{drinks}=2; my $p = \%hash; my %copy = %{ $p }; use Data::Dumper; print Dumper( \%hash, \%copy, $p ); __END__ $VAR1 = { 'a' => { 'drinks' => 1 }, 'b' => { 'drinks' => 2 } }; $VAR2 = { 'a' => $VAR1->{'a'}, 'b' => $VAR1->{'b'} }; $VAR3 = $VAR1;
        Just so you know, Data::Dumper is part of every perl
        Every modern Perl, of course:
        $ corelist Data::Dumper Data::Dumper was first released with perl 5.005