为什么我的perl脚本没有从正则表达式匹配中找到错误的缩进



我的工作的编码标准使用这个括号缩进:

some declaration
    {
    stuff = other stuff;
    };
control structure, function, etc()
    {
    more stuff;
    for(some amount of time)
        {
        do something;
        }
    more and more stuff;
    }

我正在写一个perl脚本来检测不正确的缩进。以下是我在while(<some-file-handle>)正文中的内容:

# $prev holds the previous line in the file
# $current holds the current in the file
if($prev =~ /^(t*)[^;]+$/ and $current =~ /^(?<=!$1t)[{}].+$/) {
    print "$file @ line ${.}: Bracket indentation incorrectn";
}

这里,我想匹配:

  • $prev:不以分号结尾的行,后面跟着…
  • $current:行有前导制表符的数目+前一行的1。

这似乎不匹配任何东西,目前

$prev变量需要修改。

应该是t*然后.+然后不以semicolon结尾

同样,$current应该像

任何以;{}结尾的不包含前导制表符的数目+前一行的1。

编辑用perl代码试试$prev

#!/usr/bin/perl -l
open(FP,"example.cpp");
while(<FP>)
{
  if($_ =~ /^(t*)[^;]+$/) {
    print "got the line: $_";
  }
}
close(FP);
//example.cpp

for(int i = 0;i<10;i++)
{
  //not this;
  //but this
}

//输出

got the line: {
got the line:   //but this
got the line: }

它没有检测到带有for循环的行…

我看到几个问题…

  1. 你的前一个正则表达式匹配所有没有;任何地方。它会在这样的行中中断(for int x = 1;x & lt;10;x + +)
  2. 如果开头{的缩进不正确,您将无法检测到。

试试这个,它只关心在末尾是否有一个;{(后跟任何空格)

/^(s*).*[^{;]s*$/

现在你应该改变你的策略,这样如果你看到一行不是以{或;您增加缩进计数器。

如果你看到一行以};或者}递减缩进计数器。

比较所有行
/^t{$counter}[^s]/ 

所以…

$counter = 0;
if (!($curr =~ /^t{$counter}[^s]/)) {
    # error detected
}
if ($curr =~ /[};]+/) {
  $counter--;
} else if ($curr =~ /^(s*).*[^{;]s*$/) }
  $counter++;
}

对不起,我没有按照你的标准设计我的代码…:)

您打算只计算缩进的制表符(而不是空格)吗?

编写这种检查器是很复杂的。想想所有可能使用大括号而不改变缩进的结构:

s{some}{thing}g
qw{ a b c }
grep { defined } @a
print "This is just a { provided to confuse";
print <<END;
This {
  $is = not $code
}
END

但无论如何,如果上面的问题对您来说不重要,请考虑在您的正则表达式中分号是否重要。毕竟,写

while($ok)
    {
    sort { some_op($_) }
        grep { check($_} }
        my_func(
            map { $_->[0] } @list
        );
    }

应该是可能的

你考虑过Perltidy吗?

Perltidy是一个Perl脚本,它将Perl代码重新格式化为设置的标准。当然,您所拥有的不是Perl标准的一部分,但是您可以通过Perltidy使用的配置文件调整大括号。如果其他方法都失败了,您可以破解代码。毕竟,Perltidy只是一个Perl脚本。

我还没有真正使用过它,但它可能值得研究一下。您的问题是试图找到所有不同的边缘情况,并确保正确地处理它们。您可以解析100个程序,发现第101个程序揭示了格式化程序中的问题。Perltidy已经被成千上万的人在数百万行代码中使用。如果有问题,可能已经被发现了

最新更新