How to combine printf and readline in Perl

眉间皱痕 提交于 2019-12-14 02:37:07

问题


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('--> ');

回答1:


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: ';

Or, you can make STDOUT flush more often:

local $| == 1;

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: ');


来源:https://stackoverflow.com/questions/15373892/how-to-combine-printf-and-readline-in-perl

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