【问题标题】:Why doesn't my regular expression work with Perl's Switch module?为什么我的正则表达式不适用于 Perl 的 Switch 模块?
【发布时间】:2009-07-25 09:12:30
【问题描述】:

我想使用 switch 语句。我很快就遇到了困难。看来我倒霉了。我决定使用 if else 风格的开关。

我想知道为什么这不起作用。那你呢?正则表达式上的 /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);
 } 

有人建议使用类似 case (m!\G\sobject\s+(\w+)\s:\s*(\w+)!gc) 的方法。它没有。

【问题讨论】:

    标签: perl switch-statement


    【解决方案1】:

    Switch.pm 是使用源过滤器实现的,这可能会导致难以追踪的奇怪错误。我不推荐在生产代码中使用 Switch,因为它的不可预测性。 Switch.pm 文档还 mention 表示它在解析带有修饰符的正则表达式时可能会遇到问题。

    如果您使用的是 Perl 5.10,则可以改用新的内置 given/when 语法。

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

    如果您使用的是 5.10 之前的版本,最好的办法可能是使用 if/else 结构。

    【讨论】:

    • 我也相信 Switch 模块会在 5.10.1 中被弃用,在 5.12 中被移除。
    • 它也没有像它应该设置的那样设置$_
    【解决方案2】:

    请查看"Limitations" section of the documentation。建议您使用“m?...?”形式的正则表达式。克服一些解析问题。这可能对你有用。

    或者,查看perlsyn(1) 部分关于 switch 语句:

    切换语句

      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; }
          }
    

    【讨论】:

      【解决方案3】:

      我在网上找到的文档 (here) 似乎暗示你不能在你的正则表达式上使用额外的修饰符。

      您的代码,没有 /gc,为我编译并运行..(但没有任何意义..因为 pos 没有做需要的事情!

      use warnings;
      use strict;
      

      然后提供第二个样本,其中 $file 已初始化。

      编辑: 看看 Friedo 和 Inshalla 关于使用 Perl 5.10 的“given - when”构造的建议!就是这样!

      【讨论】:

      • 说真的,每个人,使用警告;使用严格;它真的会为你省去很多痛苦。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-03
      • 2011-03-16
      • 2020-08-28
      • 1970-01-01
      • 2022-08-18
      • 2011-09-05
      • 1970-01-01
      相关资源
      最近更新 更多