Arvind
Arvind

Reputation: 717

Does Perl's $| setting affect system commands?

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

Upvotes: 4

Views: 953

Answers (3)

brian d foy
brian d foy

Reputation: 132914

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.

Upvotes: 5

Chas. Owens
Chas. Owens

Reputation: 64949

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.

Upvotes: 5

Xetius
Xetius

Reputation: 46934

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.

Upvotes: 7

Related Questions