tags:

views:

144

answers:

3

I am looking at some old code in Perl, where the author has writtern $| = 1 in the first line.

But the code does not have any print statements, it calls a C++ binary using the system command. Now I read that $| will force flush after every print. So does it affect the system command's output in any way or am I safe to remove that line.

Thanks Arvind

+6  A: 

I do not believe so. The $| will affect the way that Perl is running, not any external executable.

You should be safe to remove it.

perldoc - perlvar : States "If set to nonzero, forces a flush right away and after every write or print on the currently selected output channel.". I think the important thing here is the "currently selected output channel". The external application will have it's own output channel.

Xetius
+5  A: 

With questions like this it is often easy to write a trivial program that shows what the behavior is:

#!/usr/bin/perl

use strict;
use warnings;

if (@ARGV) {
    output();
    exit;
}

print "in the first program without \$|:\n";
output();

$| = 1;
print "in the first program with \$|:\n";
output();

print "in system with \$|\n";
system($^X, $0, 1) == 0
    or die "could not run '$^X $0 1' failed\n";

$| = 0;
print "in system without \$|\n";
system($^X, $0, 1) == 0
    or die "could not run '$^X $0 1' failed\n";

sub output {
    for my $i (1 .. 4) {
     print $i;
     sleep 1;
    }
    print "\n";
}

From this we can see that setting $| has no affect on programs run through system.

Chas. Owens
+5  A: 

This is something that you can easily check yourself. Create a program where buffering matters, like printing a series of dots. You should see the output all at once after ten seconds since the output is buffered:

#!perl

foreach ( 1 .. 10 )
    {
    print ".";
    sleep 1;
    }

print "\n";

Now, try setting $| and calling this with system:

 % perl -e "$|++; system( qq|$^X test.pl| )";

For my test case, the $| value didn't affect the buffering in the child process.

brian d foy