in reply to How would you rewrite this?

instead of testing for
... if defined $result_ref->{'agency_id'} && $result_ref +->{'agency_id'} != 0
you can just use
... if $result_ref->{agency_id}
(unless there are agency_id values that are not numbers and you want to skip the if expression on them... but this would be generating warnings with your code, so I suppose there aren't)