AxleUK has asked for the wisdom of the Perl Monks concerning the following question:

Opps, may have posted in the wrong board by accident, is there I way I can move it? - Update: Sorted, my thanks to the gods.

I've been seeing weird behaviour where regex matches and the $1 .. $X variables seem to get clobbered when using Switch.pm.

EXAMPLE:

sub onSay { my ($playerData, $message) = @_; my @userDetails = getPlayerProperties($playerData); &printDebug('[ON SAY]','INPUT: ' . $message); switch($message) { case m/xxkick #?(\d+) (.+)/i { my $toKick = $1; my $reason = $2; &printDebug('[ON SAY]',"$toKick, $1 || $2, $reason"); } case m/xxban #?(\d+)\s+(\d+)\s+(.+)/i { my $toKick = $1; my $banLength = $2; my $banReason = $3; &printDebug('[ON SAY]',"$1, $2, $3"); } } } #-------------- # Output: #-------------- # 05/10/2010 @ 00:15:05 [ON SAY]: INPUT: xxkick 1206 test # 05/10/2010 @ 00:15:05 [ON SAY]: SGR<1206><STEAM_0:1:2161308><Spectat +or>, SGR<1206><STEAM_0:1:2161308><Spectator> || say, say

Surely the above SHOULD read:

05/10/2010 @ 00:15:05 [ON SAY]: INPUT: xxkick 1206 test 05/10/2010 @ 00:15:05 [ON SAY]: 1206, 1206 || test, test

Am I doing anything obviously wrong? I can replicate this every time and have come across it before, using if, elsif etc. works as it should. i.e.

if ($message =~ m/xxkick #?(\d+) (.+)/i) { my $toKick = $1; my $reason = $2; &printDebug('[ON SAY]',"$toKick, $1 || $2, $reason"); }

Works as it should. Any ideas?

Replies are listed 'Best First'.
Re: Switch.pm Regular Expression matches getting clobbered?
by chromatic (Archbishop) on Oct 04, 2010 at 23:40 UTC

    That's endemic to how Switch works, unfortunately. If you're using Perl 5.10 or newer, you can use the given/when construct instead.

      Thanks for the heads up on given/when - not heard of it before.