为什么 ||= 不适用于数组? [英] Why doesn't ||= work with arrays?

查看:54
本文介绍了为什么 ||= 不适用于数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 ||= 运算符来为变量提供默认值,例如

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?

推荐答案

因为 || 是一个标量运算符.如果 @array||= 1..3; 工作,它会在标量上下文中评估 1..3 ,这不是你想要的.它还在标量上下文中评估数组(这没关系,因为标量上下文中的空数组是假的),除了您不能分配给 scalar(@array).

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;

但请注意,无法区分从未初始化的数组和已分配空列表的数组之间的区别.它不像标量,您可以在其中区分 undef 和空字符串(尽管 ||= 不区分它们).

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 发现了这条 perl.perl5.porters 消息(官方 Perl 开发人员的邮件列表)详细介绍了这一点.

eugene y found this perl.perl5.porters message (the official Perl developers' mailing list) that goes into more detail about this.

这篇关于为什么 ||= 不适用于数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆