Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

string - using ternary operator while printing in perl

Here is my code:

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 "
";
} 

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this version:

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 "
";
}

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

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

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

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 ) }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...