在perl中打印时使用三元运算符 [英] using ternary operator while printing in perl

查看:182
本文介绍了在perl中打印时使用三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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中出错。错误是:

Its a really simple code. I got it working in Java, though it gives an error in Perl. The error is :

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

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

I'm new to Perl. How can I get it working?

推荐答案

试试这个版本:

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语句的部分周围添加大括号并使用 elsif 而不是否则,如果

You need to add braces around the then-part of if statements and use elsif instead of else if.

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

Without the + in the print statement, perl parses the statement as:

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

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

ie. it will use the value returned by print as the first argument to the ternary operator. Another solution is to write:

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

这篇关于在perl中打印时使用三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆