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

发布于 2024-09-29 01:01:41 字数 391 浏览 8 评论 0原文

我开发了一个脚本(主要通过访问多个解决方案并将我最喜欢的混合在一起)来查找和替换文件中的单词。这些文件都包含在一个目录中。由于某种原因,我的脚本进入无限循环,但它似乎有效。

我希望能解释一下为什么它不会退出循环。

#!/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;
}

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

世界和平 2024-10-06 01:01:41

这就是为什么在编写 Perl 时(以及使用 严格):

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

This is why you should always enable warnings when writing Perl (as well as using strict):

$ perl -e 'use warnings; my $i; $i =+ 1'
Reversed += operator at -e line 1.
﹉夏雨初晴づ 2024-10-06 01:01:41
$i=+1;

应该是

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

前者会在每个循环中将 $i 设置为 +1 (即 1),它总是小于 $count (在你的case),所以循环不会退出。

$i=+1;

should be

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

The former will set $i to +1 (i.e. 1) in every loop, which in always less than $count (in your case), so the loop won't exit.

瑕疵 2024-10-06 01:01:41

当您想知道为什么某些变量没有您期望的值时,请开始检查这些值:

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

您会立即发现您没有像您想象的那样递增 $i

这是基本的调试实践。深入研究该程序,直到您发现它没有按照您的想法进行操作为止。验证每一步的一切。

并且,打开警告。 :)

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.

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. :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文