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
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.