ylzhang
ylzhang

Reputation: 1108

perl hash reference's reference

my $hash_ref = { a => 1, b => 2 };
my $tmp_ref = $hash_ref;

The code is as above and I want to change hash's value and insert some new pairs. my question are as follows:

  1. how can i achieve these by $tmp_ref
  2. Is it possible to change or insert by reference's reference?
  3. Is it consistent among reference's reference, reference and concrete data structure (here is hash)?

thanks a lot!

Upvotes: 1

Views: 291

Answers (2)

user47322
user47322

Reputation:

In this case, $tmp_ref is not a reference to $hash_ref, it is simply a copy of whatever $hash_ref's value is.

You can access the hash with $tmp_ref like you would with $hash_ref:

$tmp_ref->{a}; # 1

$tmp_ref->{foobar} = "hi";
$tmp_ref->{foobar}; # "hi"

In case you actually wanted to make $tmp_ref a reference to $hash_ref, here is how you'd access the original hash:

$tmp_ref = \$hash_ref;
${$$tmp_ref}{a};

Upvotes: 3

mu is too short
mu is too short

Reputation: 434865

Both $hash_ref and $tmp_ref will refer to the same hash so you can add something to $hash_ref with:

$tmp_ref->{c} = 3;

Then both $hash_ref and $tmp_ref will pointrefer to the same (a => 1, b => 2, c => 3) hash.

References are Perl's version of pointers.

Upvotes: 2

Related Questions