Search code examples
perlsubroutine

How can I check if a subroutine returns *nothing*


How can I determine that a perl function return nothing not even undef?

Examples:

sub test {
   return;
}

or

sub test {}

The problem is that the curious acting function can also return strings, lists, ... and is a part of a foreign package. So I cannot check with test() || undef because empty lists or strings will be overitten with undef.

Does anyone have an idea how I can check the "null" value, so I can create an conditional exception?


Solution

  • If you use return and you specify no return value, the subroutine returns an empty list in list context, the undefined value in scalar context, or nothing in void context.

    If no return is found and if the last statement is an expression, its value is returned. If the last statement is a loop control structure like a foreach or a while, the returned value is unspecified. The empty sub returns the empty list.

    -perlsub

    In both of your cases it will return empty list. So you cannot distinguish between them.

    If I understood you correctly you are trying to avoid empty list being overridden with undef if you do test () || undef. But that doesn't matter. In Perl both empty list and undef are considered false.

    All of the below evaluate to false

    0
    '0'
    undef
    ''  # Empty scalar
    ()  # Empty list
    ('')