Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl -- DBI selectall_arrayref when querying getting Not Hash Reference

I am very new to perl (but from a c# background) and I am trying to move some scripts to a windows box. Due to some modules not working easily with windows I have changed the way it connects to the DB. I have an sqlserver DB and I had a loop reading each row in a table, and then within this loop another query was sent to select different info. I was the error where two statements can't be executed at once within the same connection. As my connection object is global I couldn't see an easy way round this, so decided to store the first set of data in an array using:

my $query = shift;
    my $aryref = $dbh->selectall_arrayref($query) || die "Could not select to array\n";
    return($aryref);

(this is in a module file that is called)

I then do a foreach loop (where @$s_study is the $aryref returned above)

  foreach my $r_study ( @$s_study ) {
    ~~~             
    my $surveyId=$r_study->{surveyid};  <-------error this line
 ~~~~               
        };

When I run this I get an error "Not a hash reference". I don't understand?! Can anyone help!

Bex

like image 375
Bex Avatar asked Jun 16 '26 18:06

Bex


2 Answers

You need to provide the { Slice => {} } parameter to selectall_arrayref if you want each row to be stored as a hash:

my $aryref = $dbh->selectall_arrayref($query, { Slice => {} });

By default, it returns a reference to an array containing a reference to an array for each row of data fetched.

like image 139
Eugene Yarmash Avatar answered Jun 19 '26 11:06

Eugene Yarmash


$r_study->{surveyid} is a hashref

$r_study->[0] is an arrayref

this is your error. You should use the second one

like image 29
benzebuth Avatar answered Jun 19 '26 11:06

benzebuth