views:

110

answers:

3

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;
}
+13  A: 
$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.

KennyTM
Thanks. Obviously I'm new to perl.
Vasto
+15  A: 

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.
Sinan Ünür
+5  A: 

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

brian d foy