Kuncík Kuncík - 6 months ago 7
Perl Question

How to: cat text | ./script.pl

I started using

Term::Readline
recently, but now I realized
cat text | ./script.pl
doesn't work (no output).

script.pl snippet before (working ok):

#!/usr/bin/perl
use strict;
use warnings;

$| = 1;
while (<>) {
print $_;
}


script.pl snippet after (working only interactively):

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

$| = 1;
my $term = Term::ReadLine->new('name');
my $input;
while (defined ($input = $term->readline('')) ) {
print $input;
}


Is there anything I can do to preserve this behavior (to have the lines printed) ?

Answer

You need to set it up to use the input and output filehandles that you want. The docs don't spell it out, but the constructor takes either a string (to serve as a name), or that string and globs for input and output filehandles.

use warnings;
use strict;

use Term::ReadLine;

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

while (my $line = $term->readline()) {
    print $line, "\n";
}

Now

echo "hello\nthere" | script.pl

prints the two lines with hello and there, while scipt.pl < input.txt prints out the lines of the file input.txt.

The Term::ReaLine itself doesn't have much detail but realize that this is a front end for other modules, listed there. Their pages have far more information. Also, I believe that uses of this are covered elsewhere, for example in the good old Cookbook.