Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Return array from sub or return empty array

by Cow1337killr (Monk)
on Jul 05, 2016 at 03:28 UTC ( #1167199=note: print w/replies, xml ) Need Help??


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; }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1167199]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2022-01-22 17:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:












    Results (63 votes). Check out past polls.

    Notices?