简体   繁体   中英

Discarding extra newlines on STDIN in Perl without Term::ReadKey

I've been digging through search engine results and Stack Overflow trying to solve this problem, and I've tried a dozen different "solutions" to no avail. I cannot use Term::ReadKey, as most solutions suggest, due to limitations of my environment.

The existing Perl script does:

my $mode1=<STDIN>;
chomp($mode1);

but many of the prompts don't evaluate the input - for example the user could enter an arbitrary string - but the script only chomps the input and then ignores the contents. Several prompts ask for input but pressing [ENTER] without entering input applies default values.

If the user gets impatient while the script is in a blocking function or checks to see if the terminal is responding by pressing [ENTER], those newline characters advance the script inappropriately when the blocking function ends. I don't want to rely on user training instead of automation, and it seems like there must be an easy obvious solution but I can't seem to dig one up.

It isn't originally my script, and its author admits it was quick-and-dirty to begin with.

The 4-argument select function is a little cryptic to use, but it can tell you, in many cases, whether there is any unread input waiting on an input filehandle. When it is time for your program to prompt the user for input, you can use select to see if there is any extra input on STDIN , and clear it before you prompt the user again and ask for additional input.

print "Prompt #48: are you tired of answering questions yet? [y/N]";
clearSTDIN();
$ans48 = <STDIN>;
...

sub clearSTDIN {
    my $rin = "";
    vec($rin, fileno(STDIN), 1) = 1;
    my ($found,$left) = select $rin,undef,undef,0;
    while ($found) {
        # $found is non-zero if there is any input waiting on STDIN
        my $waste = <STDIN>;   # consume a line of STDIN
        ($found,$left) = select $rin,undef,undef,0;
    }
    seek STDIN,0,1;   # clears eof flag on STDIN handle
}

Is the easy solution to close STDIN ?

print "Are you sick of answering questions yet? [y/N] ";
$ans = <STDIN>;
if ($ans =~ /^y/i) {
    close STDIN;
    # from now on, further calls to <STDIN> will immediately
    # return  undef  and will assign default values
}
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM