Perl 是否有相当于 C# 中空合并运算符 (??) 的功能?
我开始非常喜欢 C# 的 ?? 运算符。我已经习惯了这样一个事实,即在某种语言中有方便的东西的地方,很可能在 Perl 中也有。
但是,我找不到?? Perl 中的等效项。有吗?
I started to really like C#'s ?? operator. And I am quite used to the fact, that where there is something handy in some language, it's most probably in Perl too.
However, I cannot find ?? equivalent in Perl. Is there any?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
从 5.10 开始,有
//
运算符,如果您认为 Perl 中undef
的概念等同于null 在 C# 中。
示例 A:
示例 B:
As of 5.10 there is the
//
operator, which is semantically equivalent if you consider the concept ofundef
in Perl to be equivalent to the concept ofnull
in C#.Example A:
Example B:
正如亚当说< /a>,Perl 5.10 有
//
运算符,用于测试其左侧操作数的定义性而不是真实性:如果您使用的是早期版本的 Perl,则有点混乱。
||
不起作用:在这种情况下,如果
$this
为 0 或空字符串(两者均已定义),您将得到$那个。为了解决这个问题,习惯用法是使用条件运算符,这样您就可以进行自己的检查:
As Adam says, Perl 5.10 has the
//
operator that tests its lefthand operand for defined-ness instead of truth:If you are using an earlier version of Perl, it's a bit messy. The
||
won't work:In that case, if
$this
is 0 or the empty string, both of which are defined, you'll get$that
. To get around that, the idiom is to use the conditional operator so you can make your own check:实际上,短路 OR 运算符在评估 undef 时也可以工作:
但是,在评估 0 but true 时它会失败:
Actually, the short-circuit OR operator will also work when evaluating undef:
However, it will fail when evaluating 0 but true:
这个问题暗示了任意数量的参数,所以答案意味着一个子例程:
在这里你明白了 - 将返回列表的第一个定义/非空字符串值:
The question implied any number of arguments, so the answer implies a subroutine :
Here you get it - will return the first defined/non empty-string value of a list :
据我所知没有。
Perl 并不是 null 概念的真正大用户。它确实可以测试变量是否未定义。没有像 ?? 这样的特殊运算符不过,您可以使用条件 ?: 运算符进行 undef 测试并非常接近。
我在 perl 运算符列表 要么。
Not that I know of.
Perl isn't really a big user of the null concept. It does have a test for whether a variable is undefined. No special operator like the ?? though, but you can use the conditional ?: operator with an undef test and get pretty close.
And I don't see anything in the perl operator list either.