views:

55

answers:

1

What is the right way to stop an endless while-loop with a Term::Readline::readline?

This way I can not read in a single 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;

and with

last if not defined $con;

the loop does never end.

+3  A: 

You can do it the way it is shown in the 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";

Output:

C:\Temp> t

input: one

input: two

input:^D
You entered:
one
two
Sinan Ünür
`length` will throw a warning if $con is ever undefined
Eric Strom
You are realizing that Ctrl-D under Unix/Linux is Ctrl-Z under Windows?
gorilla
@gorilla Why don't you try it with CTRL-Z under Windows and let me know what you find out.
Sinan Ünür