June 2008
Beginner
352 pages
11h 16m
English
Here’s one way to rewrite the number-guessing program from
Chapter 10. We don’t have to use a
smart match, but we do use given:
use 5.010;
my $Verbose = $ENV{VERBOSE} // 1;
my $secret = int(1 + rand 100);
print "Don't tell anyone, but the secret number is $secret.\n"
if $Verbose;
LOOP: {
print "Please enter a guess from 1 to 100: ";
chomp(my $guess = <STDIN>);
my $found_it = 0;
given( $guess ) {
when( ! /^\d+$/ ) { say "Not a number!" }
when( $_ > $secret ) { say "Too high!" }
when( $_ < $secret ) { say "Too low!" }
default { say "Just right!"; $found_it++ }
}
last LOOP if $found_it;
redo LOOP;
}In the first when, we check
that we have a number before we go any further. If there are
nondigits, or even just the empty string, we head off any warnings
in the numeric comparisons.
Notice that we don’t put the last inside the default block. We actually did that first,
but it causes a warning with Perl 5.10.0 (but maybe that warning
will go away in future versions).
Here’s one way to do it:
use 5.010;
for (1 .. 105) {
my $what = '';
given ($_) {
when (not $_ % 3) { $what .= ' fizz'; continue }
when (not $_ % 5) { $what .= ' bin'; continue }
when (not $_ % 7) { $what .= ' sausage' }
}
say "$_$what";
}Here’s one way to do it:
use 5.010;
for( @ARGV )
{
say "Processing $_";
when( ! -e ) { say "\tFile does not exist!" }
when( -r _ ) { say "\tReadable!"; continue }
when( -w _ ) { say "\tWritable!"; continue }
when( -x _ ) { say "\tExecutable!"; continue }
}We don’t ...