in reply to Re: I have a hash in a hash in a .....
in thread I have a hash in a hash in a .....

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

Replies are listed 'Best First'.
Re^3: I have a hash in a hash in a .....
by ikegami (Patriarch) on Feb 21, 2006 at 20:37 UTC

    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

        I said the result was read-only. I never said $r was read-only. Oops, I didn't original post, but I did in my second post. Fixed.

        The OP wanted a means of accessing the value at "key" @k.
        Using the "$r" method, one cannot edit the accessed value.
        Using the "$p" method, one can edit the accessed value.

        When something cannot be edited, it is said to be read-only. So while the scalar $r itself is not read-only, the accessed value is read-only.

        Update: Added underlined text.