那里有很多,因为 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})
有人也有一篇关于“秘密操作员”的非常有趣的文章,如下所示:
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?
还有什么值得补充的吗?还有哪些其他条件集变量可用于减少代码?还缺少什么?