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

Hi, Im relatively new to perl and im having an issue. Ive simplified what I have been doing to make it easy to show my problem. this is my code:

#/usr/bin/perl use POSIX; use warnings; use strict; use diagnostics; use Data::Dumper; #variables to hold DA values so they can be used for checks my @DA; my %rec; my @DA_head=qw(bu_name bu_start bu_end); my $bu1="passJeune100MMS,-1,1180656000,1201823940;passJeune10MMS,10,11 +80656000,1200441540"; my @buckets=split(';',$bu1); #add all buckets within each bucket string into array foreach (@buckets) { my ($bu_name,$bu_amount,$bu_start,$bu_end)=split(',', $_); #write the DA values into the array @rec{@DA_head} = ($bu_name,$bu_start,$bu_end); print "$_\n"; push @DA, \%rec; print Dumper(\@DA); }

My problem is I want both values from @buckets in @DA but what seems to be happening is that I get a second element in the array but the first element is being overwritten by the new value from @buckets instead of being added as the second element.

Any help would be greatly appreciated, Rizz

Replies are listed 'Best First'.
Re: Pushing values into an array of hashes
by RichardK (Parson) on Aug 09, 2012 at 14:55 UTC

    I think you'll find the problem is you're pushing a reference to %rec to your @DA each time, but you only have one instance of %rec, i.e. all your references point to the same thing.

    So if you move the definition of %rec inside the loop it should do what you want.

    So something like this

    for (@buckets) { my %rec; ... push @DA,\%rec; }
      Cheers, It worked perfectly :)
Re: Pushing values into an array of hashes
by Anonymous Monk on Aug 10, 2012 at 01:05 UTC
    Any and every time you see "values being overwritten" ... references are always the ultimate reason why. You have multiple references to the same piece of storage. The storage is being overwritten and every reference, no matter where it may be (surprise!!) reflects it.