user1685185
user1685185

Reputation:

Perl: Error printing after do-while loop

I am making a concatenating do-while loop wherein each of the entered strings will be added to the main string $food. Here is the code:

do {
  print("\nEnter your order(-1 to end): ");
  $order = <>;
  chop($order);

  if ($order != -1) {
   $food .= " ".$order;
   print($food);
  }  
} while ( $order != -1)

print ($food); #PROBLEM HERE!

The problem is that whenever I put print ($food) outside the loop, a syntax error for this line appears plus an Execution of file.pl aborted due to compilation errors message.

The code works once I put print ($food) inside the loop but I am curious to why this error is happening.

Upvotes: 0

Views: 306

Answers (2)

Jarmund
Jarmund

Reputation: 3205

A thing worth mentioning in addition to the syntax error: I see that you you start the string with a newline. While this is fine, it might be considered "better" to end strings with the newline before printing, as printing a newline would result in flushing the STDOUT buffer right away. In most cases, this is the behavior you want, as it prevents delayed output and text flickering (especially if printing a lot).

Upvotes: 0

mvp
mvp

Reputation: 116157

Your line before last print has syntax error - it does not end with ;. Just add it and it should work.

Upvotes: 3

Related Questions