2

Here is my code sample:

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

This displays partial correct results, if a number if divisible by 3, it displays the "number" and not "Divisible by 3".

Example of output:

1
2
3
4
Divisible by 5
6
7
8
9
Divisible by 5

PS: I have to write this code in the minimum no. of characters possible. (The reason why the code is so sluggish)

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
xan
  • 4,640
  • 13
  • 50
  • 83
  • Duplicate: http://stackoverflow.com/questions/14650715/using-ternary-operator-while-printing-in-perl – squiguy Feb 01 '13 at 17:13
  • @squiguy: that started out as a different question; this question was added later, but I've rolled it back now – ysth Feb 01 '13 at 20:45

3 Answers3

3

The fourth line is parsed as

(((($i % 3) == 0) ? ($s = 'Divisible by 3') : $s) = $i)

meaning that even when $i is divisible by 3, the assignment looks like

($s = 'Divisible by 3') = $i

Some fixes:

$i%3==0 ? ($s="Divisible by 3") : ($s=$i)
$s = ($i%3==0 ? "Divisible by 3" : $i)

Pro-tip: B::Deparse is very helpful for figuring this stuff out. I ran the command

perl -MO=Deparse,-p -e '$i%3==0 ? $s="Divisible by 3" : $s=$i'

to see exactly what the problem was.

mob
  • 117,087
  • 18
  • 149
  • 283
0

The ternary ?: has higher precedence than assignment. Use parens to sort that out:

for my $i (1 .. 100) {
   my $s = "Divisible by ";
     $i%15==0 ? ($s .= 15)
   : $i%5==0  ? ($s .= 5)
   : $i%3==0  ? ($s .= 3)
   :            ($s  =$i);
   print "$s\n";
}

Output:

1
2
Divisible by 3
4
Divisible by 5
Divisible by 3
7
8
Divisible by 3
Divisible by 5
amon
  • 57,091
  • 2
  • 89
  • 149
-1

If you want a version with less characters,

for $i(1..100){print(($i%3&&$i%5?$i:"Divisible by ".($i%5?3:$i%15?5:15))."\n");}

Parenthesis after the print function means call the print function, not group the expression. Caused by the fact that parenthesis are optional for that function.

AndyClaw
  • 740
  • 8
  • 15
  • 1
    I don't think `print (...)."\n"` does what you think it does. – mob Feb 01 '13 at 17:47
  • @mob: Yes, you are right. But how will I achieve the new line? – xan Feb 01 '13 at 17:58
  • @mob and xan I edited the answer to print the newline. I hope you are learning how perl apparently doesn't have the order of operations that you and I are guessing. – AndyClaw Feb 01 '13 at 20:47