Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Monks, I'm trying to write a snippet of code that gets the user to enter a filename until they enter one that's present. Here's the code:
$|++; use Term::ReadLine; my $term = new Term::ReadLine 'test'; while ($filename = $term->readline('>')) { print "checking for $filename...\n"; last if (-e $filename); print "file not found, try again\n"; } print "filename is ~~$filename~~";
This works fine except when I just press enter at the '>' prompt; at which point the program exits, without even getting to "checking for...". The same thing happens in the middle of my program. Obviously, I don't want this, as I then end up trying to open a file that isn't there. Is this behaviour intentional? Any ideas appreciated.

Replies are listed 'Best First'.
Re: Term::ReadLine behaviour on a blank line
by ikegami (Patriarch) on Apr 03, 2006 at 16:15 UTC
    readline returns "" when you just press enter. "" evaluates to false. Try
    while (defined($filename = $term->readline('>'))) {

    Update: While you do need to check if the returned value is defined (as opposed to just false), what I suggested is not enough to fix your program. I re-read your post, and you want to read until you get a valid file name. Why then is your loop terminated when there is nothing to read? Try this:

    use Term::ReadLine; # Direct notation recommended over indirect notation. my $term = Term::ReadLine->new('test'); for (;;) { $filename = $term->readline('>'); die("Unable to read in filename\n") unless defined $filename; print "checking for $filename...\n"; last if -e $filename; print "File not found. Please try again\n"; } print "filename is ~~$filename~~";
    </c>
      Thanks, that nailed it.
Re: Term::ReadLine behaviour on a blank line
by Anonymous Monk on Apr 03, 2006 at 16:21 UTC
    Comment:
    last unless defined $filename; # this doesn't work last if $filename eq ''; # this doesn't work, either