http://www.perlmonks.org?node_id=827221

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

Dear perl -gurus: i am new to perl and really have begun to love this stuff very quickly .. I have a data structure:
my $room = ( { TEXT => $string, EXITS => $exits, THINGS => { %things }, ITEMS => { %items }, CMDS => { %cmds }, # EVENTS => \&events, } );
I have a function that pass this ref, and then read some data into the strucrture and push it onto an array several passes, that I then return a ref to .. But I end up with the last (pass) element in all places in the array .. the ref use the same memory again and again? How can I make the ref a new one in each pass? When I print it out I get the correct strings for each pass .. so it must be the push that creates a problem.
foreach (@rooms) { ($rr->{TITLE}, $rr->{TEXT}, $rr->{EXITS}, $rr->{THINGS +}, $rr->{ITEMS}) = split ":", $_; push @a, $rr; }; return \@a;
Please, anyone, how to approach this problem? Thanks .. ^^^theantler<<<
  • Comment on the ref use the same memory when i push structure onto array? Gahh .. please help me dear perl-gurus
  • Select or Download Code

Replies are listed 'Best First'.
Re: the ref use the same memory when i push structure onto array? Gahh .. please help me dear perl-gurus
by almut (Canon) on Mar 07, 2010 at 12:31 UTC

    That's the nature of references. They refer to some other thing which exists somewhere else.  If you copy just the reference (by pushing it onto the array), that copy will still refer to the same old thing.

    You have to create a new data structure for each new set of info:

    my ($title, $text, ...) = split /:/; push @a, { TITLE => $title, TEXT => $text, ... };

    Also search CPAN for various modules that allow making deep copies of data structures.

      Dear almut, thanks for your answer. I thought maybe that perl knew the values into the structure had changed and so it incremented the ref memory or something like that. But it works now, wow .. this stuff is so great. I love it. I am very grateful I also always -sofar get a qualified answer, when I ask a question here .. what a great place! I love you guys. ^^^theantler<<<
Re: the ref use the same memory when i push structure onto array? Gahh .. please help me dear perl-gurus
by eric256 (Parson) on Mar 09, 2010 at 14:11 UTC

    you could also just add a my $rr; at the top of the loop to make sure you where starting with a new $rr everytime through. You could also use hash slices to simply the split a little

    foreach (@rooms) { my $rr; @$rr{ qw/TITLE TEXT EXITS THINGS ITEMS/ } = split ":", $_; push @a, $rr; }; return \@a;


    ___________
    Eric Hodges