perl - (m/regexp/)或{multiple;命令;后;要么; }

标签 perl error-handling

我非常喜欢这种语法:

try_something() or warn "Cant do it"; 

如何在or之后添加更多命令?

例如,在以下代码中将很有用:
foreach (@array)
{
   m/regex/ or {warn "Does not match"; next;}  # this syntax is wrong
   ...
}

我发现的一种方法是
try_something() or eval {warn "Can't do it"; next;}; 

但我认为这是个坏主意。

最佳答案:
  • doeval更好。
  • 逗号运算符甚至更好:do_smth() or warn("Does not match"), next;注意:warn必须带括号,这样next不会解析为其参数之一。
  • 最佳答案

    对于您的问题,我将使用unless

    for (@array) {
      unless (/regex/) {
        warn "Does not match";
        next;
      }
    
      ...
    }
    

    有时您可以使用comma operator摆脱困境。它评估其左手参数,丢弃结果,评估右手参数并返回该结果。适用于您的情况看起来像
    for (@array) {
      /regex/ or warn("Does not match"), next;
    
      ...
    }
    

    注意多余的括号。您必须对括号和以这种方式分组更加谨慎。在使用此技术时要谨慎:它很快就会变得丑陋。

    在下面的评论中,扎伊德建议
    warn('Does not match'), next unless /regex/;
    

    选择取决于风格。 Perl由语言学家创建。自然语言使我们可以根据要强调的部分以不同的方式表达相同的思想。在您的情况下,您要强调警告还是模式匹配?将更重要的代码放在前面。

    关于perl - (m/regexp/)或{multiple;命令;后;要么; },我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10799063/

    相关文章:

    vb6 - 重试运行时错误

    c - 如何验证枚举元素并最终生成错误?

    perl - 是否可以在 Perl 中增加标量引用?

    json - 如何在perl中检查hash key是否包含JSON?

    error-handling - try catch 并不总是适用于冰 CoffeeScript

    python - 展平图层ValueError : Input 0 is incompatible with layer flatten_5: expected min_ndim=3, found ndim=2

    php - 当cakePHP的 Controller 中不存在函数时,保存错误

    Perlcritic 配置 - 查找生成错误的策略的名称?

    linux - 根据列匹配 2 个大型 csv?

    perl - DBD::Mock 为存储过程指定输出值