can you force flush output in perl

孤人 提交于 2019-12-09 08:25:56

问题


I have the following two lines in perl:

print "Warning: this will overwrite existing files.  Continue? [y/N]: \n";
my $input = <STDIN>;

The problem is that the print line does not get executed before the perl script pauses for input. That is, the perl script just seems to stop indefinitely for no apparent reason. I'm guessing that the output is buffered somehow (which is why I put the \n in, but that doesn't seem to help). I'm fairly new to perl, so I would appreciate any advise on how to get around this issue.


回答1:


By default, STDOUT is line-buffered (flushed by LF) when connected to a terminal, and block-buffered (flushed when buffer becomes full) when connected to something other than a terminal. Furthermore, <STDIN> flushes STDOUT when it's connected to a terminal.

This means

  • STDOUT isn't connected to a terminal,
  • you aren't printing to STDOUT, or
  • STDOUT's been messed with.

print prints to the currently selected handle when no handle is provided, so the following will work no matter which of the above is true:

# Execute after the print.
# Flush the currently selected handle.
# Needs "use IO::Handle;" in older versions of Perl.
select()->flush();

or

# Execute anytime before the <STDIN>.
# Causes the currently selected handle to be flushed immediately and after every print.
$| = 1;



回答2:


There are several ways you can turn on autoflush:

$|++;

at the beginning, or also with a BEGIN block:

BEGIN{ $| = 1; }

However, it seems to be something unusual with your configuration, because usually a \n at the end triggers the flushing (at least of the terminal).




回答3:


use IO::Handle;
STDOUT->flush();



回答4:


To those who don't want to call flush() following every print like a baby-sitter thing, because it might be in a loop or something and you simply want your print to be unbuffered, then simply put this at the top portion of your perl script:

STDOUT->autoflush(1);

Thereafter, no need to call flush() after print.




回答5:


Yes. I made a subroutine for this in my util.pl file, which is required in all my Perl programs.

###########################################################################
# In: File handle to flush.
# Out: blank if no error,, otherwise an error message. No error messages at this time.
# Usage: flushfile($ERRFILE);
# Write any file contents to disk without closing file. Use at debugger prompt
# or in program.
sub flushfile
{my($OUTFILE)=@_;
my $s='';

my $procname=(caller(0))[3]; # Get this subroutine's name.

my $old_fh = select($OUTFILE);
$| = 1;
select($old_fh);

return $s; # flushfile()
}



来源:https://stackoverflow.com/questions/33812618/can-you-force-flush-output-in-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!