Search code examples
perl

How do I return an empty array / array of length 0 in perl?


I want to return an empty array, not an empty list.

I have a sub that returns an array of things. I want to be able to do this with it:

my $count = scalar getArray();

I did it like this:

sub getArray {
    if ( !isGood() ) {
        return ();
    } else {
        my @array = calculateSomehow();
        return @array;
    }
}
my $count = scalar getArray();

I had a suprise when !isGood() and $count becomes undef, not 0! After reading perlfaq4, I realize that this is because getArray() is evaluated in scalar context and hence the list () is evaluated as a scalar, and scalar( () ) is undef, while my @array; scalar( @array ) is 0.

The question now becomes: How do I most elegantly return an empty array, so that $count is 0 if !isGood()? I've only come up with:

# This is kind of kludgy: Dereference an anonymous array ref. Really?
return @{[]};

or

# I use a temporary variable for this. Really?
my @empty;
return @empty;

Aren't there any cleaner / more elegant ways of returning an array of length 0 (empty array) or some other way of making scalar getArray() evaluate to 0?


Solution

  • It's probably clearest if you just return an array in both cases:

    sub getArray {
        my @array;
        @array = calculateSomehow() if isGood();
        return @array;
    }
    

    But to modify your original code in the minimal way, use wantarray.

    if (!isGood()) {
        return wantarray ? () : 0;
    }