I’m very new to Perl and I’m confused with exactly how its variable scope works.
I’m trying to create an array of Hashes from the result of a MySQL query.
The following code works, as intended, without use strict
my %hash = ();
while (my %hash = %{$qhand->fetchrow_hashref()} ) {
push(@results, {%hash});
}
but when strict is enabled it produces the following error:
Can’t use an undefined value as a HASH reference at [filename] line XX (the line of the while statement).
Could someone tell me what I’m doing wrong and what the corresponding rule in strict is that I’m flaunting?
You’re violating the
refsportion of strict. When you try to use a non-reference value as a reference, Perl wants to create a “symbolic reference”, which is usually not what you want although it silently continues the program (probably not “working”, but just continuing). By enabling strictures, you catch those cases.In your example and Jonathan’s answer, it looks like you are doing a lot of acrobatics to undo hash references just to make them hash references again. Is there a reason you don’t just leave it as a hash reference?
And, if you just want to get all the results as hash references, there’s a DBI method for that so you can skip the
whileloop: