Perl中提供了哪种语法糖来减少l/rvalue运算符与if语句的代码? [英] What kind of syntactic sugar is available in Perl to reduce code for l/rvalue operators vs. if statements?
问题描述
那里有很多,因为Perl是一种非常含糖的语言,但是任何一种语言中最常用的语句是if语句和设置值的组合.我想我找到了很多,但是仍然有一些差距.最终,目标是不必多次写一个变量名:
There's a bunch out there, as Perl is a pretty sugary language, but the most used statements in any language is the combination of if statements and setting values. I think I've found many of them, but there's still a few gaps. Ultimately, the goal would be to not have to write a variable name more than once:
这是我到目前为止所拥有的:
Here's what I have so far:
$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, 0, 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})
某人在秘密操作员"上还有一条真正有趣的文章,如下所示:
Somebody also had a really interesting article on a "secret operator", shown here:
my @part = (
'http://example.net/app',
( 'admin' ) x!! $is_admin_link,
( $subsite ) x!! defined $subsite,
$mode,
( $id ) x!! defined $id,
( $submode ) x!! defined $submode,
);
但是,我发现列表中缺少的是:
However, what I've found to be missing from the list is:
$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?
还有其他值得补充的地方吗?还有哪些其他条件设置变量可用于减少代码?还缺少什么?
Is there anything else worth adding? What other conditional set variables are available to reduce the code? What else is missing?
推荐答案
使用低优先级的and
和or
关键字,可以更清楚地编写您问题中的这些结构:
These structures from your question could be written a little bit more clearly using the low precedence and
and or
keywords:
$c and return $r; # return $r if ($c);
$c or return $r; # return $r unless ($c);
$c and $r = $s; # $r = $s if ($c);
and
和or
的好处是,与语句修饰符控制字不同,and
和or
可以链接到复合表达式中.
The nice thing about and
and or
is that unlike the statement modifier control words, and
and or
can be chained into compound expressions.
另一个用于语法糖的有用工具是将for
/foreach
循环用作单个值的主题划分器.请考虑以下内容:
Another useful tool for syntactic sugar is using the for
/foreach
loop as a topicalizer over a single value. Consider the following:
$var = $new_value if defined $new_value;
vs
defined and $var = $_ for $new_value;
或类似的东西
$foo = "[$foo]";
$bar = "[$bar]";
$_ = "[$_]" for $foo, $bar;
map
函数也可以以这种方式使用,并且具有可以使用的返回值.
the map
function can also be used in this manner, and has a return value you can use.
这篇关于Perl中提供了哪种语法糖来减少l/rvalue运算符与if语句的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!