1

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

3 Answers 3

15

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.
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Thanks. Obviously I'm new to perl.
5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.