Because ||
is a scalar operator. If @array||= 1..3;
worked, it would evaluate 1..3
in scalar context, which is not what you want. It's also evaluating the array in scalar context (which is ok, because an empty array in scalar context is false), except that you can't assign to scalar(@array)
.
To assign a default value, use:
@array = 1..3 unless @array;
But note that there's no way to tell the difference between an array that has never been initialized and one that has been assigned the empty list. It's not like a scalar, where you can distinguish between undef
and the empty string (although ||=
doesn't distinguish between them).
eugene y found this perl.perl5.porters message (the official Perl developers' mailing list) that goes into more detail about this.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…