# third option: sub process { my ($data, $filter) = @_; # lengthy calculations with $data here ... # in that length calculation you have to decide # if you continue with your calculation: if ($filter) { for (@$data){ if ($filter->($_)) { push @$data, other_lengthy_calculation($_); } } } else { for (@$data){ push @$data, other_lengthy_calculation($_); } }