【问题标题】:simple perl regular expression doesn't seem to work简单的 perl 正则表达式似乎不起作用
【发布时间】:2015-06-24 01:32:53
【问题描述】:

Perl 新手在这里。我不明白为什么下面的代码不起作用:

use strict;

my $file = shift;
open(FRED,'<',$file);
while (my $line = <FRED>) {
    if ($line ~= /(fred)/i) {
    print("$line mentions fred.\n");
    }
}

我不断收到以下错误:

syntax error at ./regex2.pl line 11, near "$line ~"

syntax error at ./regex2.pl line 14, near "}"

./regex.pl 的执行由于编译错误而中止。

【问题讨论】:

    标签: regex perl


    【解决方案1】:

    匹配运算符(=~) 的波浪号在右侧,而不是左侧:

    if ($line ~= /(fred)/i) {
    

    应该是:

    if ($line =~ /(fred)/i) {
    

    【讨论】:

    • 谢谢你们。就是这样!
    【解决方案2】:

    正则表达式的语法是=~ 而不是~= 所以试试

    if($line =~ /fred/i) {
        print "$line mentions fred.\n";
    }
    

    【讨论】:

      【解决方案3】:

      问题是这样的:

      运算符是 =~ 而不是 ~=

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-05
        相关资源
        最近更新 更多