Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re^2: STDIN Enter key not quite working

by Marshall (Canon)
on Apr 05, 2021 at 23:53 UTC ( [id://11130876]=note: print w/replies, xml ) Need Help??


in reply to Re: STDIN Enter key not quite working
in thread STDIN Enter key not quite working

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11130876]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (6)
As of 2024-04-18 22:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found