perl - 更新命令行输出

标签 perl backspace output-formatting

我的程序(碰巧在 Perl 中,虽然我认为这个问题不是特定于 Perl 的)在程序中的某一点输出状态消息 Progress: x/yy哪里xyy是一个数字,例如: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/

相关文章:

c++ - 为什么我的 "double"值没有按我预期的方式打印?

c - 打印多维字符数组

linux - 单字母十六进制的 Perl 正则表达式语法

linux - 不要成功将 perl 解释器包含到 vim 中

javascript - 跟踪是否在输入字段中按下了退格键或删除键

android - 在 Android 4.x 的 Phonegap 下,无法让退格键在 codemirror 中工作?

Perl - 使用 DBD Oracle 时出现文件过多错误

regex - 有没有办法让 "allow"一个 perl RegEx 在尝试匹配时一次忽略 1 个字符?

javascript - 防止退格键在 AngularJS 中导航回来

python - 如何将嵌套字典的内容写入特定格式的文件?