【问题标题】:How to concatenate reverse if statement to string?如何将反向if语句连接到字符串?
【发布时间】:2017-01-15 21:47:57
【问题描述】:
use DateTime::Format::Natural;
$parser = new DateTime::Format::Natural;
$dt = $parser->parse_datetime("1 Test 2010");
print "Date: " . ($dt->dmy('/') if $parser->success);

为什么最后一行没有编译?

【问题讨论】:

标签: string perl if-statement concatenation


【解决方案1】:

它不能编译,因为if 的形式是一个语句修饰符;它只能用在语句的末尾,不能用在表达式的其他地方。

你可以这样做:

print "Date: " . ( $parser->success ? $dt->dmy('/') : '' );

或:

print "Date: " . do { $dt->dmy('/') if $parser->success };

(尽管后者会尝试打印 $parser->success 如果它是假的,并且在这种情况下它会打印“Date: 0”)。

【讨论】:

    【解决方案2】:

    也许在这里使用三元运算符?

    print 'Date: ' . ($parser->success ? $dt->dmy('/') : '');
    

    或者将代码拆分成两条语句;

    print 'Date: ';
    print $dt->dmy('/') if $parser->success;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-18
      • 2011-11-12
      • 1970-01-01
      • 2016-12-03
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多