Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Answer: How do you test for return type($,@,%)?

( #20523=categorized answer: print w/ replies, xml ) Need Help??

Q&A > subroutines > How do you test for return type($,@,%)? contributed by QandAEditors

A subroutine may only know whether its caller wants a SCALAR or an ARRAY. The wantarray function handles this.
sub test { if (wantarray){ return 'One String'; } else { return ('A', 'List', 'of', 'Strings'); } }
There is no built-in way to tell if a subroutine's caller wants a hash, but davorg has posted a sample of how you would do this (see his answer).

The DBI module uses a similar technique (non-relevant code removed for brevity):

sub fetchall_arrayref { my $slice= shift || []; my $mode = ref $slice; if ($mode eq 'ARRAY') { push @rows, [ @$row ] while($row = $sth->fetch); } elsif ($mode eq 'HASH') { push @rows, $row while ($row = $sth->fetchrow_hashref); } else { Carp::croak("fetchall_arrayref($mode) invalid") } return \@rows; }
If you call fetchall_arrayref with an array reference (or no reference), it will return array references. If you call it with a hash reference, it will return hash references.
$sth->fetchall_arrayref( [] ) # returns Array references $sth->fetchall_arrayref( {} ) # returns Hash references

Cool stuff!

Russ

Comment on Answer: How do you test for return type($,@,%)?
Select or Download Code
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (10)
As of 2015-07-06 17:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (77 votes), past polls