如何在perl中返回长度为0的空数组/数组?

时间:2016-03-17 21:53:35

标签: perl

我想返回一个空的数组,而不是一个空的列表

我有一个返回一系列事物的子。我希望能够用它做到这一点:

my $count = scalar getArray();

我是这样做的:

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

!isGood()$count成为undef而不是0时,我感到很惊讶!阅读perlfaq4之后,我意识到这是因为getArray()在标量上下文中进行了评估,因此列表 ()被评估为标量,scalar( () )undef,而my @array; scalar( @array )是0。

现在的问题是:如何最优雅地返回一个空的数组,以便$count 0 !isGood()如果# This is kind of kludgy: Dereference an anonymous array ref. Really? return @{[]}; ?我只想出:

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

scalar getArray()

Aren有任何更清洁/更优雅的方式来返回长度为0的数组(空数组)或其他一些方式{{1} }评价为0

2 个答案:

答案 0 :(得分:6)

如果你只是在两种情况下都返回一个数组,那么它可能是最清楚的:

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

但要以最小的方式修改原始代码,请使用wantarray

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

答案 1 :(得分:0)

返回引用,您可以通过解除引用在一次调用中获取数组大小(如果为空,则为0)。

sub getArray {
    # calculate ...
    return [ @results ];      # @results may be empty
}

$rres = getArray();
my $count = @$rres;           # gives 0 if ref is to empty array

my $cnt   = @{ getArray() };  # or without storing the return

如果您愿意,可以使用scalar,但您不需要。这也类似于返回一个指向数组的指针(即使是空的),如果这是你想要一个“空数组”的想法。

如果你想走这条路,而是单挑not-good

sub getArray {
    return if !isGood();  # returns undef
    # calculate ...
    return [ @results ];  # scalar whether the list be empty or not
}

使用context可能会有所帮助 - 你要么得到你的数组(不是空列表),要么得到标量0

sub getArray {
   if (!isGood() ) {
       return (wantarray) ? () : 0;
   }
   else { }  # your code
}
my @results = getArray() # returns a list, possibly empty
my $count = getArray();  # returns 0
相关问题