Eugen Konkov Eugen Konkov - 2 months ago 15
Perl Question

Is there a way to distinguish error and empty array returned from subroutine when it is called in list context?

I have script:

#!/usr/bin/env perl

sub t0 {
return; # We return nothing for ERROR
}

sub t1 {
@z = ();
return @z; # We return array (which maybe empty) for no ERROR
}


In scalar context I can distinguish error and OK status:

my $x1 = t0(); # undef
my $x2 = t1(); # 0


Is there a way to distinguish error and empty array returned from subroutine when it is called in list context?

my @x1 = t0(); # empty list
my @x2 = t1(); # empty list


I am feeling that I need "0E0" (Zero but TRUE) but for list context.

Answer

A way to distingish between the empty list and an error in this case would be to return an array reference, e.g.

sub t0 {
    return undef;     # We return undef for ERROR
}

sub t1 {
    @z =  ();
    return \@z;  # We return array (which maybe empty) for no ERROR
}

So basically the functions do not behave differently in list context. They always return a single scalar, which may be undef, which indicates an error, or return a reference to an array.