Can I prompt for user input after reading piped input on STDIN in Perl?

前端 未结 3 1752
名媛妹妹
名媛妹妹 2020-12-31 08:50

I\'m trying to write a perl script that reads piped data, then prompts the user for input based on that data. The following script, prompt_for_action, is what I

相关标签:
3条回答
  • 2020-12-31 09:01

    On Unix-y systems, you can open the /dev/tty pseudo-file for reading.

    while (<STDIN>) {
        print "from STDIN: $_";
    }
    close STDIN;
    
    # oops, need to read something from the console now
    open TTY, '<', '/dev/tty';
    print "Enter your age: ";
    chomp($age = <TTY>);
    close TTY;
    print "You look good for $age years old.\n";
    
    0 讨论(0)
  • 2020-12-31 09:16

    Once you pipe something through STDIN, your former STDIN (keyboard input) is being replaced by the pipe. So I don't think this is possible.

    0 讨论(0)
  • 2020-12-31 09:22

    As for non-Unix-y systems you can use the findConsole from Term::ReadLine, and then use its output like in mob's answer, e.g. instead of /dev/tty put in the output of findConsole first element.

    Example on Windows:

    use Term::ReadLine;
    while (<STDIN>) {
        print "from STDIN: $_";
    }
    close STDIN;
    
    # oops, need to read something from the console now
    my $term = Term::ReadLine->new('term');
    my @_IO = $term->findConsole();
    my $_IN = $_IO[0];
    print "INPUT is: $_IN\n";
    open TTY, '<', $_IN;
    print "Enter your age: ";
    chomp($age = <TTY>);
    close TTY;
    print "You look good for $age years old.\n";
    

    outputs:

    echo SOME | perl tty.pl
    from STDIN: SOME
    INPUT is: CONIN$
    Enter your age: 12 # you can now enter here!
    You look good for 12 years old.
    
    0 讨论(0)
提交回复
热议问题