简体   繁体   English

在C#中是否存在等效于空合并运算符(??)的Perl?

[英]Is there a Perl equivalent to the null coalescing operator (??) in C#?

I started to really like C#'s ?? 我开始真的很喜欢C#的 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. 而且我很习惯这样一个事实:在某些语言中有一些方便的东西,它最有可能也在Perl中。

However, I cannot find ?? 但是,我找不到?? equivalent in Perl. 相当于Perl。 Is there any? 有没有?

As of 5.10 there is the // operator, which is semantically equivalent if you consider the concept of undef in Perl to be equivalent to the concept of null in C#. 从5.10开始,有//运算符,如果你认为Perl中的undef概念等同于C#中的null概念,那么它在语义上是等价的。

Example A: 例A:

my $a = undef;
my $b = $a // 5;  # $b = 5;

Example B: 例B:

my $a = 0;
my $b = $a // 5;  # $b = 0;

As Adam says , Perl 5.10 has the // operator that tests its lefthand operator for defined-ness instead of truth: 正如Adam所说 ,Perl 5.10有//运算符测试其左手操作符的定义而不是真值:

 use 5.010;

 my $value = $this // $that;

If you are using an earlier version of Perl, it's a bit messy. 如果您使用的是早期版本的Perl,则会有点混乱。 The || || won't work: 不会起作用:

 my $value = $this || $that;

In that case, if $this is 0 or the empty string, both of which are defined, you'll get $that . 在这种情况下,如果$this为0或空字符串(两者都已定义),您将获得$that To get around that, the idiom is to use the conditional operator so you can make your own check: 为了解决这个问题,成语是使用条件运算符,以便您可以自己检查:

 my $value = defined( $this ) ? $this : $that;

Actually, the short-circuit OR operator will also work when evaluating undef: 实际上,在评估undef时,短路OR运算符也可以工作:

my $b = undef || 5;  # $b = 5;

However, it will fail when evaluating 0 but true: 但是,在评估0时它会失败但是为真:

my $b = 0 || 5;  # $b = 5;

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 : 在这里你得到它 - 将返回列表的第一个定义/非空字符串值:

sub coalesce { (grep {length} @_)[0] }

Not that I know of. 从来没听说过。

Perl isn't really a big user of the null concept. Perl并不是null概念的大用户。 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. 但是,您可以使用带有undef测试的条件?:运算符并且非常接近。

And I don't see anything in the perl operator list either. 我也没有在perl 运算符列表中看到任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM