Aft*_*ock 2 perl switch-statement
我想使用switch语句.我很快遇到了困难.看起来我不走运.我决定使用if else样式的开关instread.
我想知道为什么这不起作用.你呢?看起来正则表达式上的/ gc标志存在问题.
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);
}
Run Code Online (Sandbox Code Playgroud)
有人建议像case(m!\ G\s object\s +(\ w +)\ s:\ s*(\ w +)!gc)这样的东西可以工作.它不是.
fri*_*edo 13
Switch.pm是使用源过滤器实现的,这可能会导致奇怪的错误,这些错误很难被追踪.由于其不可预测性,我不建议在生产代码中使用Switch.Switch.pm文档还提到它可能无法使用修饰符解析正则表达式.
如果您使用的是Perl 5.10,则可以使用新的内置given/when语法.
use feature 'switch';
given ( $file ) {
when ( /\G\s*object\s+(\w+)\s*\:\s*(\w+)/gc ) {
...
}
}
Run Code Online (Sandbox Code Playgroud)
如果您使用的是5.10之前的版本,最好的办法就是使用if/else结构.
请查看文档的"限制"部分.建议您使用"m?...?"形式的正则表达式 克服一些解析问题.这可能对你有用.
或者,查看switch语句的perlsyn(1)部分:
切换语句
Run Code Online (Sandbox Code Playgroud)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; } }
我在网上找到的文档(这里)似乎暗示你不能在正则表达式上使用额外的修饰符.
你的代码,没有/ gc,编译并为我运行..(但没有任何意义..因为pos没有做你需要的东西!
请
use warnings;
use strict;
Run Code Online (Sandbox Code Playgroud)
然后提供初始化$ file的第二个样本.
编辑:看看弗里多和Inshalla建议使用Perl 5.10的"给 - 时"构造!这是要走的路!
| 归档时间: |
|
| 查看次数: |
7238 次 |
| 最近记录: |