in reply to Re^2: Newbie hash/sorting question
in thread Newbie hash/sorting question

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?

Replies are listed 'Best First'.
Re^4: Newbie hash/sorting question
by aaron_baugher (Curate) on Dec 09, 2011 at 17:06 UTC

    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.

      Thanks Aaron... I think the lightbulb just turned on for me.