Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

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 romping around the Monastery: (6)
As of 2018-06-23 09:02 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (125 votes). Check out past polls.