SPUG: Switch's "case" matching doesn't set $1 !

Tim Maher tim at consultix-inc.com
Tue Feb 13 10:48:11 PST 2007


The following program doesn't work as expected. As usual, that either
means that the expectations are wrong, or the code is wrong.

A perusal of the module's documentation and code didn't reveal any
obvious explanation. What's more, the docs characterize the
"case /re/" syntax as "match if $s =~ /$c/", suggesting that any
regex valid in a real matching operator should be usable.

So can somebody explain this apparently anomalous behavior?
TIA,
-Tim
P.S. I'm teaching a "Perl Fundamentals" class from 2/28-3/2.
****************************************************************
#! /usr/bin/perl -wl

use Switch;

'unset' =~ /(.*)/;      # prime $1 to contain "unset"

for ('chocolate', 'vanilla', 'swirl') {
        switch($_) {
            case /(vanilla|chocolate)/ { # () sets $1 ??
                print "The flavor of the moment is: $1"; # what's $1?
            }
            else {
                print "'$_' is not a real flavor!";
            }
        }
}

$ perl script
The flavor of the moment is: unset
The flavor of the moment is: unset
'swirl' is not a real flavor!

*-------------------------------------------------------------------*
|  Tim Maher, PhD  (206) 781-UNIX   http://www.consultix-inc.com    |
|  tim at ( Consultix-Inc, TeachMePerl, or TeachMeUnix ) dot Com    |
| Classes: 2/28: Basic Perl; 3/12: Basic UNIX/Linux; 3/16: Min Perl |
*-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-*
|  * "Minimal Perl" book rates 4.8 out of 5 stars at Amazon.com! *  |
| > Download chapters, read reviews, and order at MinimalPerl.com < |
*-------------------------------------------------------------------*


More information about the spug-list mailing list