my $matches = 0; while (...) { ++$matches; ... } if (! $matches) { ... "sorry no matches found" } #### my $command = $sth->fetchrow_arrayref(); if (! $command) { ... "sorry no matches found" } else { do { for (...) { printf ... } } while ($command = $sth->fetchrow_arrayref()); } #### my $first = 1; while ( (my $command = $sth->fetchrow_arrayref) || $first ) { if (! $command) { ... "sorry no matches found" $first = 0; } else { for ... } }