in reply to STDIN Enter key not quite working

If you don't mind the CPAN dependenc(y|ies) you might also look at something like IO::Prompter rather than reading from STDIN with the readline operator.

The cake is a lie.
The cake is a lie.
The cake is a lie.

Replies are listed 'Best First'.
Re^2: STDIN Enter key not quite working
by Marshall (Canon) on Apr 05, 2021 at 23:53 UTC
    I would have a lot of hesitancy about using that module because of this: Several features of this module are known to have problems under Windows.

    Here is a simple formula for a command loop. For user input any leading and trailing spaces are allowed (just like std unix commands). 1) print the prompt, 2)get the user line, 3) reject if it doesn't match the desired regex.

    Note: the parens around the print are required.

    use strict; use warnings; my $n_cookies; while ( (print "How many cookies do you want? Enter number: "), $n_cookies=<STDIN> and $n_cookies !~ /^\s*[1-9]\d*\s*$/) { print "invalid input! - try again!\n"; } $n_cookies +=0; # trick to convert to numeric value # which "deletes" leading/trailing zeroes # or a substitution operation would be fine print "$n_cookies cookies requested!"; __END__ Example Run: Note: allowing leading zero requires more complex regex This is just a "concept example" C:...\PerlProjects\Monks>perl commandloop.pl How many cookies do you want? Enter number: invalid input! - try again! How many cookies do you want? Enter number: 0 invalid input! - try again! How many cookies do you want? Enter number: 023 invalid input! - try again! How many cookies do you want? Enter number: 1 23 invalid input! - try again! How many cookies do you want? Enter number: abc invalid input! - try again! How many cookies do you want? Enter number: cookies 34 invalid input! - try again! How many cookies do you want? Enter number: 5 5 cookies requested!
    I made the above into a sub, but I can't find it right now. Virtually none of my programs prompt the user for input in this way in preference to Getopt or Getopt::Long.