On 11-09-05 03:22 PM, Shlomi Fish wrote:
One option would be to check that $_ matches the regular
expression /\A[1-7]\z/
Another is to write a sub you can re-use:
#!/usr/bin/env perl
use strict;
use warnings;
use Scalar::Util qw( looks_like_number );
sub choose_from_menu {
my ( @menu ) = @_;
my %choice = (); # get unique list of choices
# do loop forever, i.e. until exited by last
GET_ITEM_CHOICES:
while(1){
# prompt for input
print "\nEnter the number(s) of your choice:\n";
print "Press Ctrl-Z to signify you have finished inputting your
list.\n\n";
# display the menu, with a number for each item
my $index = 1;
for my $item ( @menu ){
printf "\t% 2d. %s\n", $index, $item;
}continue{
$index ++;
}
# can get only one choice at a time
print "\n\tEnter your choice: ";
my $anything = <STDIN>;
# if STDIN is undef, user pressed Ctrl-Z
last GET_ITEM_CHOICES unless defined $anything;
# $anything should be all digits
chomp( $anything );
# validate the user's choice
if( looks_like_number( $anything )
&& $anything >= 1
&& $anything <= @menu
){
# it's a valid number
my $number = $anything - 1;
# has it been enter before?
if( exists $choice{ $number } ){
warn "\n\n***** '$anything' is already choosen *****\n\n\n";
}else{
$choice{ $number } = 1;
}
}else{ # not a valid number
warn "\n\n***** '$anything' is not a numbered item in the list
*****\n\n\n";
}
}
# make output more readable
print "\n\n\n";
# return choices sorted as numbers
return sort { $a <=> $b } keys %choice;
}
# list of names for testing
my @names = qw/ fred betty barney dino wilma pebbles bamm-bamm /;
# call the sub
my @choosen = choose_from_menu( @names );
# show the results
print "names choosen: @names[@choosen]\n";
__END__
--
Just my 0.00000002 million dollars worth,
Shawn
Confusion is the first step of understanding.
Programming is as much about organization and communication
as it is about coding.
The secret to great software: Fail early & often.
Eliminate software piracy: use only FLOSS.
"Make something worthwhile." -- Dear Hunter
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/