I have this loop where I populate a record and attempt to push it to an array:
while (@data = $sth->fetchrow_array()) {
$rec->{'article_id'} = $data[0];
$rec->{'category_id'} = $data[1];
$rec->{'category_name'} = $data[2];
$rec->{'author_id'} = $data[3];
$rec->{'headline'} = $data[4];
$rec->{'teaser'} = $data[5];
$rec->{'author_name'} = $data[7];
push @article_data, $rec;
}
However, when this loop is done, @array_data only contains the last element which is in $rec. I have printed $rec each time through the loop, and it is populated properly, with different values each time. But, @array_data looks like this:
$VAR1 = {
'author_name' => 'Equity Research',
'author_id' => '631459560',
'teaser' => 'Barnes' (B) first-quarter 2022 revenues increase 4% year over year.',
'article_id' => '16608',
'category_name' => 'Analyst Blog : Earnings Article',
'category_id' => '298',
'headline' => 'Barnes Group (B) Q1 Earnings & Revenues Surpass Estimates'
};
$VAR2 = $VAR1;
$VAR3 = $VAR1;
$VAR4 = $VAR1;
This is the last element retrieved from the DB in the loop. Why is it not pushing each item into a different element in @article_data?
CodePudding user response:
At the start of your loop, add $rec = {};
.
Currently $rec
remains the same entity throughout the loop, you only ever overwrite the values of a given set of keys in each iteration. Therefore you end up with an array of identical copies.
CodePudding user response:
You only have one hash, and $rec
is a reference to that hash. Each pass of the loop, you add a copy of that reference to the array. So you end up with multiple reference to the one hash.
But you want multiple hashes. One for each row. I would use my %rec;
to create it.
while ( my @data = $sth->fetchrow_array() ) {
my %rec; # Create a new hash.
$rec{ article_id } = $data[ 0 ];
$rec{ category_id } = $data[ 1 ];
$rec{ category_name } = $data[ 2 ];
$rec{ author_id } = $data[ 3 ];
$rec{ headline } = $data[ 4 ];
$rec{ teaser } = $data[ 5 ];
$rec{ author_name } = $data[ 7 ];
push @article_data, \%rec;
}