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

when with Many Items

Sometimes you’ll want to go through many items, but given takes only one thing at a time. In this case, you could wrap given in a foreach loop. If you wanted to go through @names, you could assign the current element to $name, then use that for given:

use 5.010;

foreach my $name ( @names ) {
    given( $name ) {
        ...
        }
    }

Guess what? Yep, that’s too much work. (Are you tired of all of this extra work yet?) This time, let’s alias the current element of @names just so given can alias it also. Perl should be smarter than that! Don’t worry, it is.

To go through many elements, you don’t need the given. Let foreach put the current element in $_ on its own. If you want to use smart matching, the current element has to be in $_.

use 5.010;

foreach ( @names ) { # don't use a named variable!
    when( /fred/i ) { say 'Name has fred in it'; continue }
    when( /^Fred/ ) { say 'Name starts with Fred'; continue }
    when( 'Fred'  ) { say 'Name is Fred'; }
    default         { say "I don't see a Fred" }
    }

If you are going to go through several names though, you probably want to see which name you’re working on. You can put other statements in the foreach block, such as a say statement:

use 5.010;

foreach ( @names ) { # don't use a named variable!
    say "\nProcessing $_";

    when( /fred/i ) { say 'Name has fred in it'; continue }
    when( /^Fred/ ) { say 'Name starts with Fred'; continue }
    when( 'Fred'  ) { say 'Name is Fred'; }
    default         { say "I don't see a Fred" }
    }

You can even put extra statements between the when ...

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