Perl中有哪种语法糖可以减少l/rvalue运算符和if语句的代码?

Bre*_*yrd 15 perl syntactic-sugar rvalue logical-operators

有一堆,因为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, 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})
Run Code Online (Sandbox Code Playgroud)

有人还有一篇关于"秘密算子" 的非常有趣的文章,如下所示:

my @part = (
    'http://example.net/app',
    ( 'admin'  ) x!! $is_admin_link,
    ( $subsite ) x!! defined $subsite,
    $mode,
    ( $id      ) x!! defined $id,
    ( $submode ) x!! defined $submode,
);
Run Code Online (Sandbox Code Playgroud)

但是,我发现在列表中遗漏的是:

$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?
Run Code Online (Sandbox Code Playgroud)

还有什么值得补充的吗?还有哪些其他条件集变量可用于减少代码?还缺少什么?

Eri*_*rom 8

使用低优先级andor关键字可以更清楚地写出您问题中的这些结构:

$c and return $r;    # return $r if ($c);
$c or return $r;     # return $r unless ($c);
$c and $r = $s;      # $r = $s if ($c);
Run Code Online (Sandbox Code Playgroud)

约的好处and,并or是不像语句修改控制字,andor可以链接到复合表达式.

语法糖的另一个有用工具是将for/ foreachloop用作单个值的局部化器.考虑以下:

$var = $new_value if defined $new_value;
Run Code Online (Sandbox Code Playgroud)

VS

defined and $var = $_ for $new_value;
Run Code Online (Sandbox Code Playgroud)

或类似的东西:

$foo = "[$foo]";
$bar = "[$bar]";

$_ = "[$_]" for $foo, $bar;
Run Code Online (Sandbox Code Playgroud)

map函数也可以这种方式使用,并具有可以使用的返回值.


Tot*_*oto 6

还有左侧三元运算符:

$cond ? $var1 : $var2 = "the value";
Run Code Online (Sandbox Code Playgroud)

相当于:

if ($cond) {
    $var1 = "the value";
} else {
    $var2 = "the value";
}
Run Code Online (Sandbox Code Playgroud)