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

Monks, I'm writing an app which uses a simple menu interface, and I'd like to be able to test it quickly by running it with a text file as imput, thus:

$ ./myprogram.pl <inputfile.txt
where inputfile is simply a text file containing the menu options I want the program to run

inputfile.txt:

1 4 5 y n filename.in y 5 8 etc..
This is fine until the program gets to a bit of user input that needs to be entered using a Term::Readline object. The Term::Readline object does not read the commands from the file, so I have to start typing in the terminal. Does anyone know how to fix this, so I can run inputfile.txt to test the whole program?

Any ideas appreciated.

Thanks, M

Replies are listed 'Best First'.
Re: Term::Readline won't accept redirected input
by Fletch (Bishop) on Apr 12, 2006 at 15:05 UTC

    It's trying to read from /dev/tty. You'll either need to run it using something like Expect and feed it via a PTY, or change your code to behave differently depending on where STDIN is coming from.

    my $get_a_line = -t STDIN ? sub { readline( $_[0] ) } : sub { scalar <STDIN> }; ## . . . my $input $get_a_line->( $prompt );
Re: Term::Readline won't accept redirected input
by ikegami (Patriarch) on Apr 12, 2006 at 16:10 UTC

    Term::ReadLine reads from the console, not from STDIN. That said, I'm surprised I can't find an option to use STDIO for circumstances such as this one.

    I *think* you can do the following:

    my $term; if ($ENV{TESTING}) { $term = Term::ReadLine->new('My Application', \*STDIN, \*STDOUT); } else { $term = Term::ReadLine->new('My Application'); }

    or even

    my $term; if (-t STDIN) { $term = Term::ReadLine->new('My Application'); } else { $term = Term::ReadLine->new('My Application', \*STDIN, \*STDOUT); }

    The previous might simplify to:

    my $term = Term::ReadLine->new('My Application', \*STDIN, \*STDOUT);

    If that doesn't work, the following should (if you only use readline):

    use IO::Handle; { package IO::Handle; no warnings 'redefine'; sub readline { my ($self) = @_; my $line = $self->getline(); return unless defined $line; chomp($line); return $line; } } my $term; if (-t STDIN) { $term = Term::ReadLine->new('My Application'); } else { $term = *STDIN; }
Re: Term::Readline won't accept redirected input
by Anonymous Monk on Apr 13, 2006 at 09:13 UTC
    Thanks for the ideas, I'll give them a try. As always, asking a question on PerlMonks has lead me to a better understanding of how things work behind the scenes.