Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the scope of Perl's $| (OUTPUT_AUTOFLUSH) setting?

Tags:

perl

I have a Perl script running on an old CentOS 5.6 server which has Perl 5.8.8 installed. Unfortunately I can't upgrade either the OS or the version of Perl that's running on this server.

When I'm running this script from the command prompt, despite there being a $| = 1; statement at the top of the script (in the global scope), it still seems to buffer output to the console (over a ssh session).

Writes to both a log file and STDOUT are carried out by a function, for example:

#!/usr/bin/perl
$| = 1;

&writelog("Started...");

# Do work with lots of writelog'ing

&writelog("...Done.");

exit(0);

sub writelog {

    # This is greatly simplified for the purpose of this question

    my ($logentry) = @_;
    my $logfile = "/var/log/thelog.log";
    my $logline = "$logentry\n";
    print $logline;
    open (LOGFILE, ">>$logfile");
    print LOGFILE, "$logline";
    close (LOGFILE);
}

Does the value of $| only affect output in the current scope, i.e. in this case the script's global scope? Or should it, in the example above, also cause immediate flushing to STDOUT/LOGFILE by the print statements in writelog?

like image 303
Kev Avatar asked Jun 19 '17 15:06

Kev


People also ask

What is Perl’s print function?

Perl’s print function does not support truly unbuffered output—a physical write for each individual character. Instead, it supports command buffering, in which one physical write is made after every separate output command. This isn’t as hard on your system as no buffering at all, and it still gets the output where you want it, when you want it.

What does $output_AutoFlush do?

If set to nonzero, forces a flush right away and after every write or print on the currently selected output channel. By default STDOUT - the standard output is the selected channel and the default value of the $| variable is 0. That means it is buffered. $OUTPUT_AUTOFLUSH is the name of the variable when the English module is used.

What does the output variable GETC do in Perl?

Setting this variable is useful primarily when you are outputting to a pipe or socket, such as when you are running a Perl program under rsh and want to see the output as it's happening. This has no effect on input buffering. See "getc" in perlfunc for that.

Does $0 remove Perl from the PS (1) output?

Note for BSD users: setting $0 does not completely remove "perl" from the ps (1) output. For example, setting $0 to "foobar" may result in "perl: foobar (perl)" (whether both the "perl: " prefix and the " (perl)" suffix are shown depends on your exact BSD variant and version).


1 Answers

$| affects only the currently selected default output filehandle.

You can explicitly set it for a filehandle like:

LOGFILE->autoflush(1);

See http://perldoc.perl.org/perlvar.html#Variables-related-to-filehandles

like image 168
ysth Avatar answered Oct 04 '22 22:10

ysth