I use the ||=
operator to provide default values for variables, like
$x ||= 1;
I tried to use this syntax with an array but got a syntax error:
@array||= 1..3;
Can't modify array dereference in logical or assignment (||=) ...
What does it mean and how should I provide arrays with default values?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With