http://qs1969.pair.com?node_id=1167199


in reply to Return array from sub or return empty array

So, in most cases, the downstream code wants a scalar to either be some value or an empty string. The downstream code wants an array to either be some non-empty array or an empty array.

Now, maybe, I have obtained some subroutines or methods that return scalars and other subroutines or methods that return arrays. I want to use those subroutines or methods without modifying them because, if I change them, I might make a mistake and then they won’t do what I thought they were supposed to do (and everyone else on the project thought they would do).

So, wouldn’t it make sense to wrap those subroutines or methods in a subroutine that will make sure that the downstream code gets what it expects?

sub somefunc_for_scalars { my $answer = some_class->some_method(); return defined($answer) ? $answer : ''; }

Digression: If the reader wants to use Perl's // operator in the return statement, go ahead. However, it may confuse other programmers. See http://stackoverflow.com/questions/23873379/what-does-the-double-forward-slash-mean-here for a nice explanation of Perl's // operator, which is available with Perl 5.10 or later.

sub somefunc_for_arrays { my @answer = get_array2(); return @answer; }

However, somefunc_for_arrays is superfluous if it is correct for get_array2() to return some non-empty array or an empty array.

In some rare instances, the downstream code does not want an empty array. So, code somefunc_for_arrays thusly:

sub somefunc_for_arrays { my @answer = get_array2(); if (!(scalar @answer)) { die 'get_array2() returned an empty array +.' }. return @answer; }