如何在 Perl 中结合 printf 和 readline [英] How to combine printf and readline in Perl

查看:44
本文介绍了如何在 Perl 中结合 printf 和 readline的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用 readline 替换 STDIN.如果我使用 STDIN(就像在注释中一样,请参阅代码),光标在 同一行中的 printf 输出之后就可以输入了.但是使用 readline printf 输出不知何故消失了,只有 readline 提示可见.我可以插入一个打印\n";"(注释掉)在 printf 的下一行中,它将提示移到下一行并且 printf 输出可见.但是,我想在提示之后直接有一个格式化的提示和光标(同一行).printf 赋值比下面的例子要复杂一些.printf 是否可行或我有哪些选择?提前谢谢.

I'm trying to replace STDIN with readline. If I use STDIN (like in comment, see code) the cursor is ready for input right after printf output in the same line. But using readline the printf output is somehow gone and only the readline prompt is visible. I can insert a "print "\n";" (commented out) in the next line to printf which moves the prompt to the next line and printf output is visible. But, I want to have a formated prompt and the cursor directly after the prompt (same line). The printf assignment is a bit more complex than in the example below. Is it feasible with printf or what are my options? Thanx in advance.

#!/usr/bin/perl -w

use Term::ReadLine;
use Term::ReadKey;
my $term = Term::ReadLine->new('name');

printf "%-12s","Input: ";
# my $new_value = <STDIN>;
# print "\n";
my $new_value = $term->readline('--> ');

推荐答案

printf 输出延迟的原因是缓冲.为避免这种情况,您可以使用未缓冲且可能更适合此类输出的 STDERR:

The reason why the output of printf is delayed is buffering. To avoid it, you can use STDERR which is not buffered and maybe more suitable for this kind of output:

printf STDERR '%-12s', 'Input: ';

或者,您可以更频繁地刷新 STDOUT:

Or, you can make STDOUT flush more often:

local $| == 1;

另一种选择是使用 sprintf 而不是 printf 并将整个表达式放到提示中:

Another option is to use sprintf instead of printf and put the whole expression to the prompt:

my $new_value = $term->readline(sprintf '%-12s-->', 'Input: ');

这篇关于如何在 Perl 中结合 printf 和 readline的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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