On Mon, 5 Sep 2011 14:10:35 -0500
Chris Stinemetz <[email protected]> wrote:
> In exercise 3-3 from the lama book.
>
> How do you make sure the user enters a number 1 thru 7?
>
> The simple program is:
>
> #!/usr/bin/perl
> use warnings;
> use strict;
> my @names = qw/ fred betty barney dino wilma pebbles bamm-bamm /;
> print "Enter some numbers from 1 to 7, one per line, then press Ctrl-Z:\n";
> chomp(my @numbers = <STDIN>);
> foreach (@numbers) {
> print "$names[ $_ -1]\n";
> }
>
One option would be to check that $_ matches the regular
expression /\A[1-7]\z/ , where \A is the start of the string, [1-7] is any
character from 1 to 7 and \z is the end of the string. So your program becomes:
#!/usr/bin/perl
use warnings;
use strict;
my @names = qw/ fred betty barney dino wilma pebbles bamm-bamm /;
print "Enter some numbers from 1 to 7, one per line, then press Ctrl-Z:\n";
chomp(my @numbers = <STDIN>);
foreach (@numbers) {
if ($_ =~ /\A[1-7]\z/) {
print "$names[ $_ -1]\n";
}
else {
warn "Incorrect number - '$_'";
}
}
I should also note that one would use Ctrl+D instead of Ctrl+Z for EOF in
UNIX-land.
Regards,
Shlomi Fish
> Just curious.. Thanks.
--
-----------------------------------------------------------------
Shlomi Fish http://www.shlomifish.org/
Funny Anti-Terrorism Story - http://shlom.in/enemy
Chuck Norris is his own boss. If you hire him, he’ll tell your boss what to
do.
Please reply to list if it's a mailing list post - http://shlom.in/reply .
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/