【问题标题】:What is the right way to stop an infinite while-loop with a Term::Readline-readline?使用 Term::Readline-readline 停止无限循环的正确方法是什么?
【发布时间】:2010-03-19 12:54:02
【问题描述】:

Term::Readline::readline 停止无限循环的正确方法是什么?

这样我就无法阅读单个0

#!/usr/bin/env perl
use warnings; 
use strict;
use 5.010;
use Term::ReadLine;

my $term = Term::ReadLine->new( 'Text' );

my $content;
while ( 1 ) {
    my $con = $term->readline( 'input: ' );
    last if not $con;
    $content .= "$con\n";
}   
say $content;

last if not defined $con;

循环永远不会结束。

【问题讨论】:

    标签: perl terminal while-loop readline


    【解决方案1】:

    您可以按照documentation 中显示的方式进行操作:

    use strict; use warnings;
    use Term::ReadLine;
    
    my $term = Term::ReadLine->new('Text');
    
    my $content = '';
    
    while ( defined (my $con = $term->readline('input: ')) ) {
        last unless length $con;
        $content .= "$con\n";
    }
    
    print "You entered:\n$content\n";
    

    输出:

    C:\Temp> t
    
    输入:一个
    
    输入:两个
    
    输入:^D
    你进来了:
    一
    两个

    【讨论】:

    • length 将在 $con 未定义时抛出警告
    • 你知道Unix/Linux下的Ctrl-D就是Windows下的Ctrl-Z吗?
    • @gorilla 你为什么不在 Windows 下用 CTRL-Z 试试,让我知道你发现了什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-29
    • 2021-12-02
    相关资源
    最近更新 更多