BluGeni BluGeni - 3 months ago 24
Perl Question

foreach value in fetchall_arrayref

I am trying to do a foreach loop for each value in my fetchall_arrayref and am having a bit of trouble.

I have:

my $list = $sth->fetchall_arrayref({});
print Dumper($list);


which gives me:

$VAR1 = [
{
'ID_NUMBER' => '123'
},
{
'ID_NUMBER' => '456'
},
{
'ID_NUMBER' => '5666'
},
{
'ID_NUMBER' => '45645'
},
{
'ID_NUMBER' => '23422'
}
];


I am not sure how to format my foreach loop print each id_number's value. Eventually I want to run a query with each value but I can figure that out once I get this working.

Thanks for any help.

Answer

You should use fetchrow_hashref instead, and do each one individually. That will make it a lot more readable, and it does not affect performance form a database point of view.

while (my $res = $sth->fetchrow_hashref) {
  print Dumper $res;
  $sth2->execute($res->{ID_NUMBER});
}

If you wanted to do it with the fetchall_arrayref, it would work like this:

my $list = $sth->fetchall_arrayref({});
foreach my $res (@{ $list }) {
  $sth2->execute($res->{ID_NUMBER});
}