Skip to Main Content
Learning Perl, 5th Edition
book

Learning Perl, 5th Edition

by Randal L. Schwartz, Tom Phoenix, brian d foy
June 2008
Beginner content levelBeginner
352 pages
11h 16m
English
O'Reilly Media, Inc.
Content preview from Learning Perl, 5th Edition

Answers to Chapter 15 Exercises

  1. 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).

  2. 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";
    }
  3. 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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Perl, 6th Edition

Learning Perl, 6th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Beginning Perl

Beginning Perl

Curtis Ovid Poe
Learning Perl 6

Learning Perl 6

brian d foy
Mastering Perl

Mastering Perl

brian d foy

Publisher Resources

ISBN: 9780596520106Supplemental ContentErrata Page