Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re^2: Newbie hash/sorting question

by Anonymous Monk
on Dec 09, 2011 at 12:07 UTC ( [id://942634]=note: print w/replies, xml ) Need Help??


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

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.

Replies are listed 'Best First'.
Re^3: Newbie hash/sorting question
by msensay (Novice) on Dec 09, 2011 at 14:21 UTC

    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.

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://942634]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (5)
As of 2024-04-25 12:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found