0

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

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?

ysth
  • 96,171
  • 6
  • 121
  • 214
xan
  • 4,640
  • 13
  • 50
  • 83
  • 1
    To avoid fence post errors, use `for $i (1 .. 100)`. – choroba Feb 01 '13 at 16:39
  • try: else { $s = ($i % 3 == 0) ? "xyz" : $i } – quicoju Feb 01 '13 at 18:08
  • rolled back the additional question, since the user seems to have started a new question for that: http://stackoverflow.com/questions/14651297/condition-in-ternary-operator-doesnt-cause-any-change – ysth Feb 01 '13 at 18:10

1 Answers1

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 ) }
ErikR
  • 51,541
  • 9
  • 73
  • 124