icon Top 9 categories map      RocketAware > Perl >

How do I create a switch or case statement?

Tips: Browse or Search all pages for efficient awareness of Perl functions, operators, and FAQs.


Search Perl pages


By activity
Professions, Sciences, Humanities, Business, ...

User Interface
Text-based, GUI, Audio, Video, Keyboards, Mouse, Images,...

Text Strings
Conversions, tests, processing, manipulation,...

Integer, Floating point, Matrix, Statistics, Boolean, ...

Algorithms, Memory, Process control, Debugging, ...

Stored Data
Data storage, Integrity, Encryption, Compression, ...

Networks, protocols, Interprocess, Remote, Client Server, ...

Hard World
Timing, Calendar and Clock, Audio, Video, Printer, Controls...

File System
Management, Filtering, File & Directory access, Viewers, ...


How do I create a switch or case statement?

This is explained in more depth in the the perlsyn manpage. Briefly, there's no official case statement, because of the variety of tests possible in Perl (numeric comparison, string comparison, glob comparison, regexp matching, overloaded comparisons, ...). Larry couldn't decide how best to do this, so he left it out, even though it's been on the wish list since perl1.

Here's a simple example of a switch based on pattern matching. We'll do a multi-way conditional based on the type of reference stored in $whatchamacallit:

      for (ref $whatchamacallit) {

        /^$/            && die "not a reference";

        /SCALAR/        && do {
                                last SWITCH;

        /ARRAY/         && do {
                                last SWITCH;

        /HASH/          && do {
                                last SWITCH;

        /CODE/          && do {
                                warn "can't print function ref";
                                last SWITCH;

        # DEFAULT

        warn "User defined type skipped";


Source: Perl FAQ: Perl Language Issues
Copyright: Copyright (c) 1997 Tom Christiansen and Nathan Torkington.
Next: How can I catch accesses to undefined variables/functions/methods?

Previous: What's the difference between calling a function as &foo and foo()?

(Corrections, notes, and links courtesy of RocketAware.com)

[Overview Topics]

Up to: PERL

Rapid-Links: Search | About | Comments | Submit Path: RocketAware > Perl > perlfaq7/How_do_I_create_a_switch_or_case.htm
RocketAware.com is a service of Mib Software
Copyright 2000, Forrest J. Cavalier III. All Rights Reserved.
We welcome submissions and comments