【问题标题】:using ternary operator while printing in perl在 perl 中打印时使用三元运算符
【发布时间】:2013-01-17 00:37:34
【问题描述】:

这是我的代码:

for($i=1;$i<=100;$i++){
   if($i%15==0) print "Divisible by 15";
   else if($i%5==0) print "Divisible by 5";
   else print ($i%3==0)? "Divisible by 3":$i;
   print "\n";
} 

这是一个非常简单的代码。我让它在 Java 中工作,虽然它在 Perl 中给出了一个错误。错误是:

syntax error at line 2, near ") print"
Execution aborted due to compilation errors.

我是 Perl 的新手。我怎样才能让它工作?

【问题讨论】:

  • 为避免围栏发布错误,请使用for $i (1 .. 100)
  • 尝试:否则 { $s = ($i % 3 == 0) ? "xyz" : $i }
  • 回滚了附加问题,因为用户似乎已经为此提出了一个新问题:stackoverflow.com/questions/14651297/…

标签: string perl int ternary-operator


【解决方案1】:

试试这个版本:

for($i=1;$i<=100;$i++){
   if ($i%15==0) { print "Divisible by 15" }
   elsif($i%5==0) { print "Divisible by 5" }
   else { print +($i%3==0)? "Divisible by 3":$i; }
   print "\n";
}

您需要在 if 语句的 then 部分周围添加大括号,并使用 elsif 而不是 else if

如果print 语句中没有+,perl 会将语句解析为:

print(...)  ?  "Divisible by 3"  :  $i;

即。它将使用print 返回的值作为三元运算符的第一个参数。另一种解决方案是这样写:

    else { print( $i % 3 == 0 ? "..." : $i ) }

【讨论】:

  • +1 括号中的要点与预期的不同。
  • 请查看我编辑的问题。你的建议是正确的,但我还有一个小疑问。
猜你喜欢
  • 1970-01-01
  • 2021-06-01
  • 2020-12-26
  • 2017-01-18
  • 2012-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多