Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

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!


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

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

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (6)
As of 2015-12-01 05:18 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (794 votes), past polls