加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

perl – 如何测试定义和返回值或某个默认值

发布时间:2020-12-15 21:44:48 所属栏目:大数据 来源:网络整理
导读:在我的代码中,我经常写这样的东西: my $a = defined $scalar ? $scalar : $default_value; 要么 my $b = exists $hash{$_} ? $hash{$_} : $default_value; 有时哈希很深,代码不是很易读.是否有更简洁的方法来完成上述任务? 解决方法 假设您使用的是Perl 5.
在我的代码中,我经常写这样的东西:
my $a = defined $scalar ? $scalar : $default_value;

要么

my $b = exists $hash{$_} ? $hash{$_} : $default_value;

有时哈希很深,代码不是很易读.是否有更简洁的方法来完成上述任务?

解决方法

假设您使用的是Perl 5.10及更高版本,则可以使用//运算符.
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

请注意,在上面的示例中,我正在检查已定义的$hash {$_},而不是像您一样存在$hash {$_}.没有像定义那样存在的简写.

最后,你有// =运算符,所以你可以做;

$a = $x unless defined $a;  # clunky
$a //= $x;                  # nice

这类似于|| =,它对真理做同样的事情:

$a = $x unless $x;  # Checks for truth,not definedness.
$a ||= $x;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读