in reply to I have a hash in a hash in a .....

The read-only result is in $r after the following snippet executes:

my $r = $my_hash_ref; $r = $r->{$_} foreach @k;

The read-write result is in $$p after the following snippet executes:

my $p = \$my_hash_ref; $p = \($$p->{$_}) foreach @k;

Replies are listed 'Best First'.
Re^2: I have a hash in a hash in a .....
by brian_d_foy (Abbot) on Feb 21, 2006 at 20:14 UTC

    Read-only result? I'm not sure what you mean by that, but if you assign to an element of $r, that affects $my_hash_ref. They're all references so they're pointing at the same data.

    #!/usr/bin/perl use Data::Dumper; my $hash = { a => { ab => { ac => 'fred' }, abb => 'barney' }, b => 'betty', c => { cb => 'dino' }, }; my $r = $hash; my @k = qw( a ab ); print Dumper( $hash ); $r = $r->{$_} foreach @k; $r->{ 'ac' } = 'Mr. Slate'; print Dumper( $hash );
    --
    brian d foy <brian@stonehenge.com>
    Subscribe to The Perl Review

      You didn't change $r the accessed value in your snippet — you changed that which is pointed by $r — so you failed to disprove that $r the accessed value is read-only.

      Say you want to do $my_hash_ref->{$k[0]}->{$k[1]}->{$k[2]} = 3;. Compare

      use Data::Dumper; my $my_hash_ref = { a => { b => { c => 2 } } }; my @k = qw( a b c ); my $r = $my_hash_ref; $r = $r->{$_} foreach @k; $r = 3; print Dumper($my_hash_ref); # { 'a' => { 'b' => { 'c' => 2 } } };

      with

      use Data::Dumper; my $my_hash_ref = { a => { b => { c => 2 } } }; my @k = qw( a b c ); my $p = \$my_hash_ref; $p = \($$p->{$_}) foreach @k; $$p = 3; print Dumper($my_hash_ref); # { 'a' => { 'b' => { 'c' => 3 } } };

      Update: Fixed a terminology error.

        Perhaps you could define "read-only", because I can certainly change $r. I can just assign it a new value. I can change the data it points to. None of those things relate to "read-only". It's the conpletely wrong way to think about it.

        That $r no longer is a reference when I give it another value doesn't really matter.

        --
        brian d foy <brian@stonehenge.com>
        Subscribe to The Perl Review