Nano HE
Nano HE

Reputation: 1971

Question on Reg Expressions used in Perl switch statement

Perl Version: 5.8 ActivePerl used.

I tried to insert reg expressions as individual conditions for switch statement in Perl, but failed.

Could you tell me more about how to fix?

I looked up per doc and can't find this kind of example. Thanks.

while (my $line =<$fh>) { # change foreach to while
    switch ($line) {
        case ($line =~ m/\<IDCateA\sName="(\w+)\"\sid="(\w+)\"\s/)  {print "            $1 = $2,\n";}
        case ($line =~ m/\<IDCateB\sName="(\w+)\"\sid="(\w+)\"\s/)  {print "            $1 = $2,\n";}
    }
    my $nextline = <$fh>;
}

A part of the data as this,

 <IDCateA Name="SystemAlpha" id="0" units="" min="0" max="8" default="0" value="3"/>
 <IDCateB Name="SystemBeta" id="1" units="" min="0" max="2" default="0" value="0"/>

Upvotes: 1

Views: 798

Answers (2)

ysth
ysth

Reputation: 98398

Avoid using Switch.pm; it is implemented using brittle technology. I believe that it executes regular expressions in a scope inside the Switch module such that $1, etc., aren't available in your code (after removing the $line =~ that don't belong there).

Your codepad example is missing use Switch. I had trouble getting Switch to cooperate with __DATA__, too.

perldoc -q switch shows a number of ways to have a switch-like statement if you can't use 5.10.1's given/when syntax, for instance:

use strict;
use warnings;

while (my $line = <DATA>) {
    for ($line) {
        if (/<IDCateA\sName="(\w+)"\sid="(\w+)"\s/) {print "  $1 = $2,\n"}
        elsif (/<IDCateB\sName="(\w+)"\sid="(\w+)"\s/) {print "   $1 = $2,\n"}
    }
}

__DATA__
<IDCateA Name="SystemAlpha" id="0" units="" min="0" max="8" default="0" value="3"/>
<IDCateB Name="SystemBeta" id="1" units="" min="0" max="2" default="0" value="0"/>

Upvotes: 4

tchrist
tchrist

Reputation: 80423

You should be using given or foreach with when from 5.10 or better, not the old deprecated Switch.pm module.

Upvotes: 4

Related Questions