matze77 has asked for the wisdom of the Perl Monks concerning the following question:

#!/usr/bin/perl use strict; use warnings; my $alter = "3"; #assign a value to alter different than 0 or 1 which is used later ... my $openfile = "$ENV{SystemRoot}/win.ini"; { open (MYFILE, ">>$openfile")or die "Can't open file 1: $!\n"; #open fo +r write, append not read! open (TEST, "c:/windows/win.ini") or die "Cant open file $!\n"; while(<TEST>) { if ( $_ =~ /[ARTEC]/ ) { my $alter = 1; } else { my $alter = 0; } } } if ($alter == 1) { #do something; print ".."; } close(MYFILE); close(TEST);

snippet of win.ini
blabla [ARTEC] IniFile=f:\vaa\basis\vaa01.ini bla
It seems like the while block never gets executed, any help?
Thx in Advance
MH
Update, Changed it now works:
not using my to declare variables ...
use vars qw($change $alter); $alter = 0; sub readfile { while(<TEST>) { if ( $_ =~ /^\[ARTEC\]$/ ) { $alter = 1; exit print "found it exiting no need to change something"; }else { $change = 1; print "n "; } } return; } } if ($alter == 0 and $change == 1) { #do something ... print "changed\n"; }

Replies are listed 'Best First'.
Re: search and replace pattern inside file not working as expected
by Corion (Patriarch) on Jan 04, 2010 at 15:54 UTC

    How did you determine that your while loop never gets executed?

    Also, /[ARTEC]/ likely does not match what you expect it to match, given your input file. See perlre about character classes. Most likely, you wanted /^\[ARTEC\]$/.

      Yes. You are right. It would match any, but not the "string" of the uppercases "ARTEC" which is not what i wanted. I "tested" it by putting print statements into the loops now. It works with the new pattern. But i made another mistake the variable needs to be assigned "globally" outside the while loop or my next if block never gets executed. Any hint? ... How could i declare the variable to work outside the loop my and local wont do ...?


      Thanks
      MH

Re: search and replace pattern inside file not working as expected
by toolic (Bishop) on Jan 04, 2010 at 15:59 UTC
    It looks like a variable scoping issue. You set $alter to 3 outside your while loop. Inside your while loop, you declare another variable, also named $alter, which is different from the $alter outside your while loop. Then you check $alter after your while loop. Since it is still 3, if ($alter == 1) evaluates to false.

    You can prove this to yourself with more liberal usage of print (tip #2 from the Basic debugging checklist), such as inside your while loop.

    In the future, receiving help would be much more efficient if you provide a smaller code example which is completely self-contained (not relying on external files). Using perltidy before posting would also make your code clearer.

    Update:

    not using my to declare variables ...
    You can replace:
    use vars qw($change $alter);
    with:
    my ($change, $alter);
    Further reading in the Tutiroals section: Variables and Scoping