RatKing has asked for the wisdom of the Perl Monks concerning the following question:

Dear monks,

I have the following code:
my $result = my_function(); if ( ref $result eq 'SCALAR' ) { # Handle scalar return value } elsif ( ref $result eq 'ARRAY' ) { # Handle Array return value }

Which works quite well till I have my_function return not a scalar or an array but a reference to one of these two options. At that point ref $result will always tell me I am looking at an reference which is of course correct but not very handy for me to handle the output in different ways. So my question is how to detect what my reference is refering to is it a scalar or an array?

Replies are listed 'Best First'.
Re: How to detect a returns value gracefully
by citromatik (Curate) on Feb 26, 2009 at 11:00 UTC

    IMHO, a function that can return an array, a scalar, a reference to an array or a reference to a scalar is probably not well designed and is a candidate to be reformulated

    BTW, the code you posted could be better written using wantarray inside the function

    sub my_fun { # blah, blah, return wantarray ? @array : $scalar; }

    Hope this helps

    citromatik

Re: How to detect a returns value gracefully
by ELISHEVA (Prior) on Feb 26, 2009 at 08:31 UTC
    Check ref $$result instead of $result whenever ref($result) eq 'REF'.
    use strict; use warnings; my $aFoo = []; my $result = \$aFoo; print 'ref $result : ' . ref($result) . "\n"; print 'ref $$result : ' . ref($$result) . "\n";

    prints

    ref $result : REF ref $$result : ARRAY

    Best, beth

      You shouldn't use references until you've read perlref

        Care to explain what the issue is instead of spreading FUD?

Re: How to detect a returns value gracefully
by Joost (Canon) on Feb 26, 2009 at 11:43 UTC
Re: How to detect a returns value gracefully
by Fletch (Bishop) on Feb 26, 2009 at 13:42 UTC

    There's also the Damian module Contextual::Return which lets you return a magical value that behaves differently when used as different types of values (and yes, it's OK for general use).

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.