Does fetchrow_hashref return into a default value?

Viewed 78

I'm trying to write like:

my $q='select name as N from names';
my $sth=$dbh->prepare( $q ) ;
$sth->execute;
$test->{ $_->{N} } = 1 while $sth->fetchrow_hashref();

but $_ is undef. Does the return value get stored somewhere accessible without explicitly assigning it? Tim, it sure would be handy if it got stored somewhere!

1 Answers

The while loop does not always implicitly assign a value to the default operator $_. As described in perldoc perlsyn:

If the condition expression of a while statement is based on any of a group of iterative expression types then it gets some magic treatment. The affected iterative expression types are readline, the input operator, readdir, glob, the globbing operator, and each. If the condition expression is one of these expression types, then the value yielded by the iterative operator will be implicitly assigned to $_.

(...and otherwise it is not, is implied here)

To do what you want, you need to do

... while $_ = $sth->fetchrow_hashref();

Or better yet, use the idiomatic syntax:

while (my $row = $sth->fetchrow_hashref()) {
    $test->{ $row->{N} } = 1;
}
Related