rampant selectrow_array misuse

David Miller justdave at bugzilla.org
Fri Aug 26 10:30:41 UTC 2005


I noticed this happening in a couple patches up for approval tonight, 
and after discussion with LpSolit on IRC discovered that we've been 
rather careless with how we treat the results of selectrow_array and 
fetchrow_array.

Both of these functions, as their names imply, return arrays.  We have 
lots of places in the code where we run these functions and attempt to 
stick the results into a scalar.  Sometimes that does what you want, and 
sometimes it doesn't, so it's a really bad habit to get into.  Consider 
the poor newbies who are trying to learn perl by reading our code. :)

You should play it safe, and always wrap the destination variable in 
parens, so that it explicitly pulls the first element out of the array.

Consider the following:

while (my $value = $dbh->selectrow_array("SELECT foo FROM table")) {
   do something;
}

Now consider that the "foo" column in "table" allows NULLS, and that 
some of the rows scattered in the middle of that column will have null 
values.

The above code snippet will stop the first time you hit a null, because 
the while loop is looking at your $value variable and sees that you got 
an undef, which qualifies as false, so the loop exits.

while (my ($value) = $dbh->selectrow_array("SELECT foo FROM table")) {
   do something;
}

The above snippet will process all of the data in the table, regardless 
of some of the values being null.  Why?  Because the while loop is 
looking at the array containing your $value, and not $value itself.  An 
array containing an undef element is still a 1-element array, and an 
array with more than 0 elements counts as true, so the loop continues. 
When you hit the end of the data, $dbh->selectrow_array will return an 
empty array (zero elements in it), which now evaluates as false, so the 
loop exits.

-- 
Dave Miller                                   http://www.justdave.net/
System Administrator, Mozilla Foundation       http://www.mozilla.org/
Project Leader, Bugzilla Bug Tracking System  http://www.bugzilla.org/



More information about the developers mailing list