LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   what is wrong with this perl code ? STDOUT / STDERR issue ? (https://www.linuxquestions.org/questions/programming-9/what-is-wrong-with-this-perl-code-stdout-stderr-issue-590241/)

rtspitz 10-08-2007 07:16 AM

what is wrong with this perl code ? STDOUT / STDERR issue ?
 
Code:

#!/usr/bin/perl -w

print $ARGV[0],$ARGV[1];

my $ctr;
for ( $ctr = 0; $ctr < 50000000; $ctr++ ) { print ""; } # just do nothing

while ( 1 ) { print "test2\n"; sleep 1;}

this is just a heavily simplified version of my code, but exhibits the same strange behaviour.

I expect the code to do this:

- immediately print command line parameter 0 and 1
- run the for loop
- print "test2" forever


what happens on the console is this

- first it waits (for loop)
- then it prints $ARGV[0] ....
- then it runs the while loop

if I let it print to STDERR instead of STDOUT it does what I want, except that I don't want it to print to STDERR... I just don't understand what the heck is going on!

druuna 10-08-2007 07:46 AM

Hi,

Ran into this a while ago myself. I don't know the ins and outs, but this has to do with perl keeping stuff in a buffer before actually releasing/printing it.

I solved it this way:
Code:

#!/usr/bin/perl -w

$| =1; # don't keep in buffer

print $ARGV[0],$ARGV[1];

my $ctr;
for ( $ctr = 0; $ctr < 50000000; $ctr++ ) { print ""; } # just do nothing

while ( 1 ) { print "test2\n"; sleep 1;}

Hope this helps.

rtspitz 10-08-2007 12:26 PM

sneaky bastard that perl, should've consulted the cookbook fist ;-)

Arrrr !

angrybanana 10-08-2007 12:32 PM

Quote:

Originally Posted by rtspitz (Post 2917377)
sneaky bastard that perl, should've consulted the cookbook fist ;-)

Arrrr !

Keep that in mind with other languages too. I know python does the same thing.

chrism01 10-08-2007 06:53 PM

By default, OSes and langs tend to buffer a certain amt of data before sending to stdout.
This buffering speeds up the program and lessens disk wear 'n tear.
As shown above, you can force no-buffering in Perl if you need to.
I tend to use that for logfiles, as it's usually the last msg befoe a prog breaks that tells you why, but this msg 'can' be lost if the prog fails to flush the buffer before die-ing.
(Actually, I rarely use the 'die' cmd. I always try to do a controlled exit that closes files/ db handles and logs/emails error, but that only works for anticipated errors, Sometimes things just die...)


All times are GMT -5. The time now is 11:30 PM.