Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

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

by QandAEditors
on Jun 30, 2000 at 04:53 UTC ( #20523=categorized answer: print w/replies, xml ) Need Help??

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

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!


Log In?

What's my password?
Create A New User
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (2)
As of 2017-05-27 12:24 GMT
Find Nodes?
    Voting Booth?