Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't my regular expression work with Perl's Switch module?

I wanted to use a switch statement. I ran into difficulties quickly. It looks like I was unlucky. I decided to use if else style instread of the switch.

I wonder why this does not work. What about you? It looks like there is problem with /gc flags on the regular expression.

use Switch;
while ( pos($file) < length($file) ) {
   switch ($file)
   {

   case  (/\G\s*object\s+(\w+)\s*\:\s*(\w+)/gc)  {
   }
   }
   last if ( $oldpos == pos($file) );
   $oldpos = pos($file);
 } 

It was suggested that something like case (m!\G\sobject\s+(\w+)\s:\s*(\w+)!gc) would work. It does not.

like image 862
Aftershock Avatar asked Feb 06 '26 04:02

Aftershock


1 Answers

Switch.pm is implemented with source filters, which can lead to strange bugs which are very hard to track down. I don't recommend the use of Switch in production code because of its unpredictability. The Switch.pm docs also mention that it can have trouble parsing regexes with modifiers.

If you're using Perl 5.10, you can use the new built-in given/when syntax instead.

use feature 'switch';
given ( $file ) { 
    when ( /\G\s*object\s+(\w+)\s*\:\s*(\w+)/gc ) { 
        ...
    }
}

If you're using pre-5.10, the best thing is probably to use an if/else structure.

like image 113
friedo Avatar answered Feb 09 '26 09:02

friedo