while (my $row = $sth->fetch()) { for (1..$#$row) { my ($parent_id, $id) = @{$row}[$i-1, $i-0]; last if !defined($id); ... } }