Perl中可以使用什么样的语法糖来减少l / rvalue运算符的代码与if
发布时间:2020-12-15 21:14:45 所属栏目:大数据 来源:网络整理
导读:有一堆,因为Perl是一个漂亮的含糖语言,但是使用任何语言中最常用的语句是if语句和设置值的组合.我想我已经找到了很多,但还是有一些差距.最终,目标是不必多次写入变量名称: 这是我到目前为止 $r ||= $s; # $r = $s unless ($r);$r //= $s; # $r = $s unless
有一堆,因为Perl是一个漂亮的含糖语言,但是使用任何语言中最常用的语句是if语句和设置值的组合.我想我已经找到了很多,但还是有一些差距.最终,目标是不必多次写入变量名称:
这是我到目前为止 $r ||= $s; # $r = $s unless ($r); $r //= $s; # $r = $s unless (defined $r); $r &&= $s; # $r = $s if ($r); $r = $c ? $s : $t; # if ($c) { $r = $s } else { $r = $t } $c ? $r : $s = $t; # if ($c) { $r = $t } else { $s = $t } $r = $s || $t; # if ($s) { $r = $s } else { $r = $t } $r = $s && $t; # if ($s) { $r = $t } else { $r = $s = undef,untrue,etc. } $c and return $r; # return $r if ($c); $c or return $r; # return $r unless ($c); $c and $r = $s; # $r = $s if ($c); @$r{qw(a b c d)} # ($r->{a},$r->{b},$r->{c},$r->{d}) 有人也有一个really interesting article在一个“秘密操作符”,如下所示: my @part = ( 'http://example.net/app',( 'admin' ) x!! $is_admin_link,( $subsite ) x!! defined $subsite,$mode,( $id ) x!! defined $id,( $submode ) x!! defined $submode,); 但是,我发现从列表中缺少的是: $r <= $s; # read as "$r = min($r,$s);" except with short-circuiting $r = $s if (defined $s); # what's the opposite of //? $r and return $r # can that be done without repeating $r? 还有什么值得添加的吗?什么其他条件集变量可用来减少代码?还有什么缺点? 解决方法
使用低优先级和/或关键字,可以更清楚地使用您的问题的这些结构:
$c and return $r; # return $r if ($c); $c or return $r; # return $r unless ($c); $c and $r = $s; # $r = $s if ($c); 与语句修饰符控制字不同,和/或是不同的是,和/或可以链接到复合表达式中. 语法糖的另一个有用工具是使用for / foreach循环作为单一值的分配器.考虑以下几点: $var = $new_value if defined $new_value; VS defined and $var = $_ for $new_value; 或者像 $foo = "[$foo]"; $bar = "[$bar]"; $_ = "[$_]" for $foo,$bar; 也可以以这种方式使用地图函数,并具有可以使用的返回值. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |