perl - 在 Perl 中使用三元条件运算符有更短的方法吗?

标签 perl conditional-operator

如果可能的话,我想在一行中完成以下作业,而且不要太长:

my $variable = defined($self->{_some_thing_stored_here}) ? $self->{_some_thing_stored_here} : new some_function(@with_some_parameters);

是否有可能以某种类似的方式在带有“$_”的循环中获取变量以获取 if 条件的参数,以便它看起来像这样:

my $variable = defined($self->{_some_thing_stored_here}) ? $_ : new some_function(@with_some_parameters);

PD:我知道可以将条件放在变量中,但我想知道是否可以缩短它。

最佳答案

defined-or operator :

my $variable = $self->{_some_thing_stored_here} // some_function(@with_some_parameters);

需要 Perl 5.10+。

您也可以(滥用)使用 postfix foreach在定义的检查不完全是你需要的时候使用 $_ ,虽然它不是最常见的习惯用法,你应该注意不要用后缀语句修饰符声明变量,并且你不要调用任何会修改现在别名的全局 $_ 的东西。

my $variable;
$variable = check($_) ? $_ : something_else() for $self->{_some_thing_stored_here};
# make sure something_else does not clobber $_
# that would also clobber $self->{_some_thing_stored_here} !

关于perl - 在 Perl 中使用三元条件运算符有更短的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56445539/

相关文章:

linux - 查找 perl 执行脚本/路径

linux - 在 Perl 中将系统命令分配给数组

c# - 如何使用 ?字符串关键字

c - 获取错误 "lvalue required as left operand of assignment"

c++ - 用于聚合结构初始化时的三元运算符整数表达式的类型

c - 使用条件运算符找到两个数字中最小的数字

C++、三元运算符和 cout

Perl,没有子进程 w/"open"

linux - 如何解释 si_status 值

perl - 可以用一行 Perl 编写一个简单的命令行 Web 浏览器吗?