Welcome to the Monastery PerlMonks

### Re: hash ref mind blow

by duckyd (Hermit)
 on Sep 24, 2008 at 16:27 UTC 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";
Prints:
```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
```\$\$p{c}=3;
or
```\$p->{c}=3;
I just want
```\$copy{c}=3;
To change the value of %hash.
-rod

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;

or

```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

Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://713464]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (3)
As of 2024-02-23 03:20 GMT
Voting Booth?
My favourite way to spend a leap day ...

Results (22 votes). Check out past polls.