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

Hi, I'm trying to put piped input to a perl script, and then in the same script, get an input from the user. Like this,
@piped = <STDIN>; print "last piped element: ".$piped[-1]; $user_input = <STDIN>; print "user input: ".$user_input;
Then this is executed like this.. dir /b | perl test.pl please some help!

Replies are listed 'Best First'.
Re: STDIN problemo
by almut (Canon) on Dec 18, 2009 at 20:31 UTC
    #!/usr/bin/perl my @piped = <STDIN>; print "last piped element: ".$piped[-1]; close STDIN; open STDIN, "<", "/dev/tty" or die "Couldn't open console: $!"; # "con" on Windows (IIRC) print "> "; my $user_input = <STDIN>; print "user input: ".$user_input; __END__ $ echo foo |./813419.pl last piped element: foo > bar user input: bar

      re line 8 for windows: perhaps con: or CON: (either appears to work on the rather dated W32 box available right now):

      open STDIN, "<", "/con:" or die "Couldn't open console: $!";

      To execute a command * found in $user_input simply insert

      system($user_input);

      after line 11 of almut's elegant no-module solution -- which observation is in no way intended to deprecate ikegami's earlier reply using a module which also appears to fit the OP's needs. Both are easily extensible./p>

      Update: * ...but this fails with some commands, notably with cd or chdir, although it does "work" with commands like dir or perl -c script.pl.

        Thanks! that was perfect.

        Just getting to know this language or scripting language.. and i love it! i can do so many things whit so few code.

Re: STDIN problemo
by ikegami (Patriarch) on Dec 18, 2009 at 19:25 UTC

    I believe Term::ReadLine will read from the console and not STDIN.

    Update: Confirmed

    >perl -MTerm::ReadLine -le"print 'Entered: ', Term::ReadLine->new->rea +dline" < nul INPUT> Foo! Entered: Foo!
Re: STDIN problemo
by eye (Chaplain) on Dec 20, 2009 at 07:16 UTC
    Update: I got that wrong. See the correct explanation from ikegami (below).

    While the problem has been solved, it has not been explained. In the first line:

    @piped = <STDIN>;
    Reading <STDIN> in list context reads until the end of file for STDIN. At that point, you can no longer read from STDIN, so line 4 fails:
    $user_input = <STDIN>;
    The solutions suggested either avoid using STDIN for user input (reading from the console) or close and re-open STDIN.
      The problem has nothing to do with reaching the end of the file. As you can see, you can keep reading from a terminal after reaching the end of the file.
      >perl -e"for my $x (1..2) { print qq{$x: $_} while <STDIN>; }" a 1: a b 1: b c 1: c ^Z d 2: d e 2: e f 2: f ^Z

      The problem is much simpler. If STDIN was redirected away from the console, then it can't be used to read from the console. The solutions provided are alternate means of accessing the console.