-1

这是我的代码:

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 的新手。我怎样才能让它工作?

4

1 回答 1

7

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

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 ) }
于 2013-02-01T16:31:11.710 回答