Perl:打印回到行首 [英] Perl: print back to beginning of line

查看:68
本文介绍了Perl:打印回到行首的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,所以我想做的是在命令行中打印出完整的百分比,现在,我想简单地更新"屏幕上显示的数字.因此,以某种方式返回到该行的开头并对其进行更改.

例如,Windows relog.exe命令行实用程序(可以将.blg文件转换为.csv文件)可以执行此操作.如果您运行它,它将显示完成百分比.

现在,这可能是用C ++编写的. 我不知道这在perl中也是可行的吗?

解决方案

使用八进制的"\ r"或"\ 015"(又名"Return caret"又名"

> perl5.8 -e 'print "11111\r222\r3\n";'
32211
> perl5.8 -e 'print "11111\015222\0153\n";'  
32211

请不要忘记打印至少与已经打印过的最长字符串一样多的字符以覆盖所有旧字符(如您在上面的示例中看到的那样,否则这样做会保留旧字符).

要注意的另一件事是,正如迈克尔在评论中指出的那样,在进行这些打印时需要打开自动刷新功能,以使输出不会在处理的最后等待换行符. /p>

更新:请注意,另一个答案中推荐的013八进制字符实际上是垂直制表符":

> perl5.8 -e 'print "11111\013222\0133\n";'    
11111
     222
        3

Okay, so what I'm trying to do is print out a percentage complete to my command line, now, I would like this to simply 'update' the number shown on the screen. So somehow go back to the beginning of the line and change it.

For example the windows relog.exe command-line utility (which can convert a .blg file to a .csv file) does this. If you run it, it will display a percentage complete.

Now this is probably written in C++. I don't know if this is possible in perl as well ?

解决方案

Use "\r" or "\015" octal (aka "Return caret" aka "Carriage Return" character originating from typewriter days :)

> perl5.8 -e 'print "11111\r222\r3\n";'
32211
> perl5.8 -e 'print "11111\015222\0153\n";'  
32211

Just don't forget to print at least as many characters as the longest string already printed to overwrite any old characters (as you can see in example above, the failure to do so will keep old characters).

Another thing to be aware of is, as Michael pointed in the commment, the autoflush needs to be turned on while these printings happen, so that the output doesn't wait for newline character at the very end of the processing.

UPDATE: Please note that 013 octal character recommended in another answer is actually a Vertical Tab:

> perl5.8 -e 'print "11111\013222\0133\n";'    
11111
     222
        3

这篇关于Perl:打印回到行首的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆