OR (or || ) with a negative can be very confusing... and in your sample, would not do what you want. You want the user who enters anything other than "1" or "2" to be reprompted... so you want
if ( $choice != 1 && $choice != 2 ) {
As for a way to do it (just one of many, and one about which some purists will howl) is with a label and a goto:
#!/usr/bin/perl
use strict;
use warnings;
# 875438
START: print "\nEnter your choice: ";
my $choice = <>;
chomp ($choice);
if ( $choice != 1 && $choice != 2 ) {
print "INVALID CHOICE\n";
goto START;
} else {
print "\$choice: $choice \n";
}
When executed, you'll see:
>pl_test/875438.pl
Enter your choice: 4
INVALID CHOICE
Enter your choice: 3
INVALID CHOICE
Enter your choice: 2
$choice: 2
>
A better option might be to re-reorganize your program; test the $choice and if you have a 1 or a 2, do whatever it is that you want; then elsif and reprompt there.
|