2

Executon of my perl scipt is unclear to me. It doesn't execute line-per-line, and I don't know why?

Code:

#!usr/bin/perl -w
#line 200 "Level Check"
print "\n1";
$level=554;
if($level > 550){
warn "Level Higher Than 550 ($level)";
}
print "\n2";

Output:

Level Higher Than 550 (554) at Level Check line 203.

1

2

Why doesn't it output:

1

Level Higher Than 550 (554) at Level Check line 203.

2

Community
  • 1
  • 1
Miro
  • 1,778
  • 6
  • 24
  • 42

3 Answers3

11

Because STDOUT is buffered. The warning is coming through STDERR before STDOUT gets flushed.

By default warn() goes to STDERR and print goes to STDOUT. In your current code, you're seeing STDERR being flushed prior to STDOUT

You can change that behavior by adding the following at the top:

select STDERR; $| = 1;
select STDOUT; $| = 1; 

That sets STDOUT and STDERR to be unbuffered and flush on every print.

Brian Roach
  • 76,169
  • 12
  • 136
  • 161
  • You might want to note that (by default) `print` uses the `STDOUT` file descriptor, and `warn` uses the `STDERR` descriptor. Otherwise this explanation has a bit of a gap. :) – Clinton Pierce Mar 15 '11 at 19:21
  • I'll edit, but that was already implied "The warning is coming through STDERR" – Brian Roach Mar 15 '11 at 19:24
  • 1
    And you may prefer using `use IO::Handle; STDERR->autoflush; STDOUT->autoflush;` if you don't want to keep track of what `$|` does. – Oesor Mar 15 '11 at 19:32
1

As stated above, one of your problems IO-buffering.

An other problem is, that our output (after fixing the buffering-problem) will be:

 \n
 1Level Higher Than 550 (554) at Level Check line 203.\n
 2

instead of:

 1\n
 Level Higher Than 550 (554) at Level Check line 203.\n
 2\n

which I'm guessing you expect. ('\n' added for clarity). The reason might be obvious...

Paul

Bill Ruppert
  • 8,956
  • 7
  • 27
  • 44
pavel
  • 3,488
  • 1
  • 20
  • 20
1

As others have said, it's because of the buffering. Both STDOUT and STDERR are connect to a terminal (AKA tty) and output to it is buffered until a newline; then it is printed. You have:

print "\n1";

which means the 1 will be buffered until the next newline. Had you written:

print "1\n";

It would have been printed out right away.

shawnhcorey
  • 3,545
  • 1
  • 15
  • 17