如何测试是否定义并返回值或某些默认值 [英] How to test if defined and return value or some default value
问题描述
在我的代码中,我经常这样写:
In my code, I often write things like this:
my $a = defined $scalar ? $scalar : $default_value;
或
my $b = exists $hash{$_} ? $hash{$_} : $default_value;
有时哈希值很深,代码可读性不强.有没有更简洁的方法来完成上述任务?
Sometimes the hash is quite deep and the code is not very readable. Is there a more concise way to do the above assignments?
推荐答案
假设您使用的是 Perl 5.10 及更高版本,您可以使用 //
运算符.
Assuming you're using Perl 5.10 and above, you can use the //
operator.
my $a = defined $x ? $x : $default; # clunky way
my $a = $x // $default; # nice way
你也可以这样做
my $b = defined $hash{$_} ? $hash{$_} : $default; # clunky
my $b = $hash{$_} // $default; # nice
请注意,在我上面的示例中,我正在检查 defined $hash{$_}
,而不是像您那样检查 exists $hash{$_}
.存在没有定义的简写.
Note that in my example above I'm checking defined $hash{$_}
, not exists $hash{$_}
like you had. There's no shorthand for existence like there is for definedness.
最后,你有 //=
运算符,所以你可以这样做;
Finally, you have the //=
operator, so you can do;
$a = $x unless defined $a; # clunky
$a //= $x; # nice
这类似于 ||=
,它对真理做同样的事情:
This is analogous to the ||=
which does the same for truth:
$a = $x unless $x; # Checks for truth, not definedness.
$a ||= $x;
这篇关于如何测试是否定义并返回值或某些默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!