in reply to Newbie hash/sorting question

Expanding on what Eliya said:

One way to correct this (not the best, but the simplest) is to make a COPY of the %recordset each time.

That way, you get a reference to the CONTENTS at the current time, instead of the same reference.

Change your "push" statements to :

push @data, {%recordset}; # Make a reference to a COPY of the contents + of %recordset

            "XML is like violence: if it doesn't solve your problem, use more."

Replies are listed 'Best First'.
Re^2: Newbie hash/sorting question
by Anonymous Monk on Dec 09, 2011 at 12:07 UTC
    push @data, {%recordset};

    That is probably a bit inefficient, as AFAIK it copies the hash to create the anonymous hash reference. Something like this would work:

    my $recordset = {}; $recordset->{name} = "Item A"; $recordset->{price} = 9.99; push @data, $recordset; # start with a new hash reference $recordset = {}; $recordset->{name} = "Item B"; $recordset->{price} = 4.99; push @data, $recordset;

    Of course, declaring my $recordset; inside the loop where you fill @data is probably the nicest approach.

      Thanks all... I'm starting to get the gist of it. So let me make sure I get this straight. If I did the same thing as my example #2 but put it in a loop, then I do get the distinct records in the array. in other words, this example works fine:

      use strict; use warnings; use Data::Dumper; my @data; for (my $i=5, my $j=0; $i<=10, $j<=20 ; $i++, $j++) { my %recordset; $recordset{name} = $i; $recordset{price} = $j; push @data, \%recordset; } print Dumper(\@data);

      Outside of a loop, this wouldn't work and the push would overwrite what is already there. yes?

        Yes, that works, but not strictly because it's in a loop. It works because you're creating a new hash inside the scope of the loop, and pushing a reference to that new hash to your array. That hash goes out of scope at the end of the loop, so the next time through the loop, you're creating a brand new hash. If you moved my %recordset; outside the loop, you'd have the same problem as before, because it would have scope outside the loop and not be created anew each time.

        You could do the same thing outside a loop, as other people have shown, but it would be more awkward.</c>

        Aaron B.
        My Woefully Neglected Blog, where I occasionally mention Perl.