Reputation: 5351
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.
Upvotes: 2
Views: 8640
Reputation: 67028
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.
Upvotes: 14
Reputation: 8849
The documentation I found on the web (here) seems to imply you can't use additiononal modifiers on your regex.
Your code, sans the /gc, compiled and ran for me .. (but makes no sense .. since pos doesn't do what is needed!
PLEASE
use warnings;
use strict;
then provide a second sample with $file initialized .
EDIT: Take a look at Friedo's and Inshalla's suggestion of using Perl 5.10's "given - when" construct! That's the way to go!
Upvotes: 5
Reputation: 4814
Please have a look at the "Limitations" section of the documentation. It's suggested that you use regexes of the form "m? ... ?" to overcome some parsing problems. That may work for you.
Alternatively, have a look at the perlsyn(1) section on switch statements:
Switch statements
Starting from Perl 5.10, you can say use feature "switch"; which enables a switch feature that is closely based on the Perl 6 proposal. The keywords "given" and "when" are analogous to "switch" and "case" in other languages, so the code above could be written as given($_) { when (/^abc/) { $abc = 1; } when (/^def/) { $def = 1; } when (/^xyz/) { $xyz = 1; } default { $nothing = 1; } }
Upvotes: 6