Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re^3: check for wantarray?

by bageler (Hermit)
on Dec 27, 2008 at 00:46 UTC ( [id://732729]=note: print w/replies, xml ) Need Help??


in reply to Re^2: check for wantarray?
in thread check for wantarray?

If this is a problem you can call all subroutines in array context and examine the first and possible remainder of the array elements for expected return values.
@ret = somesub(); if (ref $ret[0] eq 'HASH') { .... } elsif (ref $ret[0] eq 'ARRAY') { .... }
etc. Messy but would take care of the problem. This is how I handle some XML data structures deparsed from API calls to certain applications that can return an array of hashrefs, an arrayref of hashrefs, a single hashref or undefined.

Replies are listed 'Best First'.
Re^4: check for wantarray?
by ikegami (Patriarch) on Dec 27, 2008 at 01:30 UTC

    If this is a problem you can call all subroutines in array context

    It's called list context. Arrays have nothing to do with it.

    Messy but would take care of the problem.

    Not necessarily.

    sub f { return @_ } sub g { return [ @_ ] } my $d = []; my @f = f($d); printf("%d element(s), first=%s\n", 0+@f, $f[0]); my @g = g($d); printf("%d element(s), first=%s\n", 0+@g, $g[0]);
    1 element(s), first=ARRAY(0x235f6c) 1 element(s), first=ARRAY(0x236020)

    This is how I handle some XML data structures deparsed from API calls to certain applications that can return an array of hashrefs, an arrayref of hashrefs, a single hashref or undefined.

    Let's hope not since your code can't differentiate between list of hashrefs and a single hashref. The latter is just a short list of hashrefs. (I presumed you meant "list of hashref" when you said "array of hashref" since it's impossible to return an array.)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://732729]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (6)
As of 2024-04-23 10:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found