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

Hi Monks,
I want to edit a text file while doing it line by line.
I thought the next code will work good:
#!/usr/bin/perl @folder = <*>; foreach $folder (@folder) { if (-d $folder) {opendir (DH, "$folder") or warn "can't open directo +ry $folder for read\n"; foreach $file (readdir DH) { if(!(-d $file)){print"$folder/$file\n";open(READ,"+<$folder/$file" +) or die "can't open"; while (<READ>){((s/Manual_common_macros/test_macros/ge)||(s/Manu +al_constants/test_constants/ge))&&(print READ $_)&&(print)&&($|=1);} } close(READ); } } closedir(DH); } exit;
However, it's printing out the substitutions but it's not printing to the file.

please advise me, what am I doing wrong?
Thanks in advance to all,
Moked.

Replies are listed 'Best First'.
Re: Edit a text file line by line
by poolpi (Hermit) on Apr 06, 2008 at 09:32 UTC
Re: Edit a text file line by line
by Erez (Priest) on Apr 06, 2008 at 08:40 UTC

    You need to open a file to write and print the changes to that file. Best method I know of is saving your changes to an array, opening a temp file, printing the array to the file and then renaming it to the original.

    Software speaks in tongues of man.
    Stop saying 'script'. Stop saying 'line-noise'.
    We have nothing to lose but our metaphors.

Re: Edit a text file line by line
by jwkrahn (Abbot) on Apr 06, 2008 at 18:29 UTC

    Try it like this instead:

    #!/usr/bin/perl use warnings; use strict; @ARGV = grep !-d, <*/*>; $^I = '.bak'; while ( <> ) { print STDERR "$ARGV\n" if $. == 1; s/Manual_common_macros/test_macros/g || s/Manual_constants/test_co +nstants/g; print; close ARGV if eof; } exit 0;