MikeKusold
MikeKusold

Reputation: 1632

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

Upvotes: 1

Views: 554

Answers (3)

brian d foy
brian d foy

Reputation: 132914

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

Upvotes: 5

Sinan &#220;n&#252;r
Sinan &#220;n&#252;r

Reputation: 118166

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.

Upvotes: 15

kennytm
kennytm

Reputation: 523784

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

Upvotes: 13

Related Questions