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

I am trying to open a file, and search for a srting. Once found I want to substitute it for something else and acually change the file. ie) File named "stuff.txt" contains: Code: ( text ) Hello I am Kelly Hello I am David Hello I am mark I want to find David and change it to Josh. This is how I am trying to do it, but it doesn't work.
open (FIL, "+<stuff.txt") or die "$!"; foreach $line (<FIL>){ if($line =~ m/David/){ $line =~ s/David/Josh/; } print $line; }
What am I doing wrong? I tried opening the file with ">>" and "+>>", to no avail. ???

Replies are listed 'Best First'.
Re: substitution in files
by Anonymous Monk on Aug 25, 2007 at 02:24 UTC
Re: substitution in files
by wind (Priest) on Aug 25, 2007 at 02:42 UTC

    Use Tie::File for editing a line of a file.

    Also be sure to include your code in a <code></code> tag in order for it to be readable.

    - Miller

Re: substitution in files
by Cody Pendant (Prior) on Aug 25, 2007 at 04:54 UTC
    One thing wrong with your code is that you are doing "print $line" which will print it out to screen.

    If you want to change the file you need to do "print FIL $line".



    Nobody says perl looks like line-noise any more
    kids today don't know what line-noise IS ...
Re: substitution in files
by dwm042 (Priest) on Aug 25, 2007 at 03:30 UTC
    As anonymous Monk has pointed out, these kinds of changes in a file can be handled by Perl one liners:

    ~/perl/change$ cat change.txt Hello I am Kelly. Hello I am David. Hello I am Mark. ~/perl/change$ perl -pe 's/David/Josh/i' change.txt Hello I am Kelly. Hello I am Josh. Hello I am Mark. ~/perl/change$ perl -p -i -e 's/David/Josh/i' change.txt ~/perl/change$ cat change.txt Hello I am Kelly. Hello I am Josh. Hello I am Mark.
Re: substitution in files
by hilitai (Monk) on Aug 25, 2007 at 23:31 UTC
    As Cody pointed out, you're not printing to the file.
    print $line;
    prints $line to STDOUT, not to the file. You need to specify the filehandle name in the print statement, for example,
    print FIL $line;
    .