sub get_children { my $parent_id = shift; $executed_handle = $prepared_handle->execute($parent_id); # first retrieve all the results my @results; while (my $pointer = $executed_handle->fetchrow_hashref) { push @results, $pointer->{parent_id}; } # now deal with the results foreach (@results) { $results .= $_."\n"; get_children($_); } }