我的程序(碰巧在 Perl 中,虽然我认为这个问题不是特定于 Perl 的)在程序中的某一点输出状态消息 Progress: x/yy
哪里x
和 yy
是一个数字,例如:Progress: 4/38
.
我想在打印新的状态消息时“覆盖”以前的输出,这样我就不会用状态消息填充屏幕。到目前为止,我已经尝试过这个:
my $progressString = "Progress\t$counter / " . $total . "\n";
print $progressString;
#do lots of processing, update $counter
my $i = 0;
while ($i < length($progressString)) {
print "\b";
++$i;
}
如果我在
$progressString
中包含换行符,则不会打印退格字符.但是,如果我省略换行符,则输出缓冲区永远不会刷新,也不会打印任何内容。对此有什么好的解决方案?
最佳答案
将自动刷新与 STDOUT 结合使用:
local $| = 1; # Or use IO::Handle; STDOUT->autoflush;
print 'Progress: ';
my $progressString;
while ...
{
# remove prev progress
print "\b" x length($progressString) if defined $progressString;
# do lots of processing, update $counter
$progressString = "$counter / $total"; # No more newline
print $progressString; # Will print, because auto-flush is on
# end of processing
}
print "\n"; # Don't forget the trailing newline
关于perl - 更新命令行输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5009258/