Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello!

Is there any way of changing a returned hashref from a module with another function from within the module?

Like this:

Module:

package Test; sub new{ my $class = shift; my $self = {}; bless $self, $class; } sub one{ my $self = shift; my %hash = (1 => 'unchanged'); $self]->{HASH} = \%hash; return $self->{HASH}; } sub two{ $_[0]->{HASH} = {1 => 'one'}; } 1;

Script/main:

use Test; use Data::Dumper; my $t = Test->new(); my $p = $t->one(); print "First: " . Dumper($p) . "\n\n"; $t->two; print "Second: " . Dumper($p) . "\n\n"; #expecting this to change the +$p hashref

I have tried hard to find information on how to do this but it's hard to define a search for what I want to do (terminology may be my weakness here...).

Is there any way to tie the hashref in main to the internal $self->{HASH} ?

Thanks in advance!

Replies are listed 'Best First'.
Re: Changing a returned hashref
by moritz (Cardinal) on Nov 09, 2011 at 10:02 UTC

    The problem is this piece of code:

    sub two{ $_[0]->{HASH} = {1 => 'one'}; }

    It doesn't modify the hash that $_[0]{HASH} points to, but rather stores a new reference in there. Modifying the existing hash works:

    sub two{ $_[0]->{HASH}{1} = 'one'; }
      Wow! Thanks for the fast reply! It works like a charm!

      I changed the password while being logged in so the question was unfortunately assigned to an anonymous monk, hehe.

      Just to clarify for myself, I experimented a little and found that this clarified things a bit for me:

      ${$self->{HASH}}{1} = 'one';