简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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