Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run perl binary with autoflush enabled

Tags:

process

perl

My program runs perl as a process in potentially many places with different scripts which I have inherited and would prefer not to modify needlessly if I can avoid it.

The root problem I'm facing is that my program cannot consume standard output as the perl script is executing unless autoflush is enabled (otherwise it will just get every log message instantly after the perl script has finished).

Therefore, what I'd like to do is to run perl with autoflush enabled by command line argument if possible. Something like this would be ideal:

perl -e "$| = 1" -e "foo.pl"

But obviously that doesn't work.

like image 697
Coxy Avatar asked Dec 29 '25 18:12

Coxy


1 Answers

There is a CPAN module called Devel::Autoflush that does exactly this. You would invoke it from the command line:

perl -MDevel::Autoflush your-script-name-here.pl

...and it sets autoflush mode. Looking at the source code it's pretty easy to see how it works. You could just implement it yourself if you live in a world where CPAN modules are not permitted. Just create a module as follows:

package AutoFlush;

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

1;

And then from the command line invoke it just as I described above:

perl -MAutoFlush your-script-name-here.pl

This little example module is almost identical to how Devel::Autoflush does it.

Update: And as TLP correctly points out, the following would be even simpler syntax:

package AutoFlush

STDOUT->autoflush(1);
STDERR->autoflush(1);

1;

This may pull in more code, since the syntax relies on the implicit on-demand upgrading of the STDOUT and STDERR filehandles to IO::Handle objects, but when coding for clarity and programmer efficiency first, this is an obvious improvement.

like image 148
DavidO Avatar answered Dec 31 '25 11:12

DavidO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!