Gary Merrick wrote:
>
> I'm taking a beginning Perl class, and we haven't gotten to pattern matching
> yet. I need to somehow test for user input being numeric. I think. <:-)
This is a Frequently Asked Question that can be found in the
documentation that was installed with Perl.
perldoc -q "How do I determine whether a scalar is a
number/whole/integer/float"
> The second "elsif" is where I'm hung up. It seems to catch any kind of invalid
> input, text or numeric. Also, without the first "elsif" statement, users typing
> "exit" will be given an "Invalid input" error before exiting. (sigh) Could
> somebody please point me in the right direction? Any help would be very much
> appreciated.
>
> Here's what I have so far:
>
> my $input = 'undef';
^^^^^^^
Do you want to assign the string 'undef' or the value undef?
perldoc -f undef
> until ($input eq "exit") {
> print "\nPlease type one of [list, imdb_number, exit]: ";
> chomp ($input = <STDIN>);
> if ("$input" eq "list") {
^^^^^^^^
^^^^^^^^
> # do stuff
> }
> elsif ("$input" eq "exit") {
^^^^^^^^
^^^^^^^^
> # Do nothing.
^^^^^^^^^^
Why put this in at all as the until conditional will catch it?
> # Without this part, user gets "Invalid input" message before exiting.
> }
> # This part seems to catch any kind of invalid input, and it never gets
> # to "else". Why? I guess I need to test for numeric input (if it's not,
> # it goes to "else"), and then see if the number matches one of these:
> elsif ("$input" == "0120611"||"0106308"||"0088247"||"0267804"||"0094074"||
^^^^^^^^
perldoc -q quoting
Found in /usr/lib/perl5/5.6.0/pod/perlfaq4.pod
What's wrong with always quoting "$vars"?
> "0102798"||"0120382"||"0196229"||"0272152"||"0109830") {
You need to use 'eq' instead of '==' to compare strings and you need to
compare $input to each string.
elsif ( $input eq '0120611' || $input eq '0106308' || $input eq
'0088247' || $input eq '0267804' || $input eq '0094074' || $input eq
'0102798' || $input eq '0120382' || $input eq '0196229' || $input eq
'0272152' || $input eq '0109830' ) {
Or you could shorten it a bit with a regular expression.
elsif ( $input =~
/^0(?:120611|106308|088247|267804|094074|102798|120382|196229|272152|109830)$/
) {
Or you could create a lookup hash.
my %lookup = qw(0120611 1 0106308 1 0088247 1 0267804 1 0094074 1
0102798 1 0120382 1 0196229 1 0272152 1 0109830 1);
elsif ( $lookup{ $input } ) {
> # do stuff
> }
> else {
> print "\n\tInvalid input. Please try again.\n";
> }
> }
John
--
use Perl;
program
fulfillment
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]