简体   繁体   English

为什么我的Perl脚本无限循环?

[英]Why does my Perl script loop infinitely?

I developed a script (mainly by visiting multiple solutions and mashing together my favorite) to find and replace words in files. 我开发了一个脚本(主要是通过访问多个解决方案并将我最喜欢的内容混在一起)来查找和替换文件中的单词。 The files are all contained in a directory. 这些文件都包含在目录中。 For some reason, my script goes into an infinite loop, however it appears that it works. 由于某种原因,我的脚本进入了无限循环,但是看起来可以正常工作。

I would appreciate any explanation as to why it won't exit the loop. 我希望您能解释为什么它不会退出循环。

#!/usr/bin/perl -i.bak
my $DIRECTORY = '/home/mrk28/testing/findreplace';
opendir (DIR, $DIRECTORY);
@count = readdir(DIR);
my $count = @count;
print $count-2;
my $i = 0;
while ( $i < $count ) {
   s/prods55a/sapprda/;
   $i=+1;
   print;
}

This is why you should always enable warnings when writing Perl (as well as using strict ): 这就是为什么在编写Perl时(以及使用strict )应始终启用警告的原因:

$ perl -e 'use warnings; my $i; $i =+ 1'
Reversed += operator at -e line 1.
$i=+1;

should be 应该

$i+=1;    # or, ++$i;

The former will set $i to +1 (ie 1) in every loop, which in always less than $count (in your case), so the loop won't exit. 前者将在每个循环中将$i设置$i +1 (即1),但总是小于$count (在您的情况下),因此循环不会退出。

When you wonder why some variable doesn't have the value you expect, start checking the values: 当您想知道为什么某些变量没有您期望的值时,请开始检查这些值:

while ( $i < $count ) {
    s/prods55a/sapprda/;
    $i=+1;
    warn "\$i is now $i\n";
    print;
    }

You would have seen right away that you aren't incrementing $i like you think you are. 您会立即看到,您并没有像想象中那样增加$i

It's a basic debugging practice. 这是基本的调试实践。 Drill down into the program until you reach the level where you find it's not doing what you think it is. 深入研究该程序,直到达到发现它没有达到自己所想的水平为止。 Verify everything at each step. 验证每一步的所有内容。

And, turn on warnings. 并且,打开警告。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM