while (my $rows = $sth->fetchall_arrayref(undef, 3)) { # ^ this condition is always true # why? because when there is nothing to fetch, # $rows is reference to an empty array, not undef last if ($#$rows < 0); # break out of infinite loop for (@$rows) { ...