【问题标题】:Is there a shorter way of using the ternary conditional operator in Perl?在 Perl 中使用三元条件运算符有更短的方法吗?
【发布时间】:2019-06-05 04:10:37
【问题描述】:

如果可能的话,我想在一行中完成以下任务,并且不会太长:

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:我知道可以将条件放入变量中,但我想知道是否可以缩短它。

【问题讨论】:

  • 有问题的运算符称为条件运算符。它只是众多三元运算符之一。固定。

标签: perl conditional-operator


【解决方案1】:

defined-or operator:

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

需要 Perl 5.10+。

你也可以(ab)使用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} !

【讨论】:

    猜你喜欢
    • 2016-07-15
    • 2012-02-22
    • 2010-10-09
    • 2022-01-06
    相关资源
    最近更新 更多