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

I'm trying to write some code that will read in a file, check to see if a line needs to changed, and then changes it if necessary. Right now it seems to me that I have to open the file for reading, read it all into an array, close the file, edit the array, open the file again and overwrite the old file with the edited array. Is there a more elegant way to do this?

Replies are listed 'Best First'.
Re: editing a file
by fs (Monk) on May 31, 2001 at 19:40 UTC
    The perlrun manpage has some switches which will let you do "in-place" file edits, something like this:
    #!/usr/bin/perl -pi.orig if(should_change($_)){ $_ = change_line($_); }
Re: editing a file
by davorg (Chancellor) on May 31, 2001 at 19:59 UTC

    You should be looking at the seek and tell functions.

    --
    <http://www.dave.org.uk>

    "Perl makes the fun jobs fun
    and the boring jobs bearable" - me

Re: editing a file
by bikeNomad (Priest) on May 31, 2001 at 19:38 UTC
    You will at least need to read the line that needs to be checked. This will probably require reading the file up to that point. However, it may be cheaper from a memory point of view to read the file to that point (not saving it), determine if the change is needed, then seek back to the beginning and process the file if the change is needed (no reason to close it in this case). Then you can:<bl>
  • Write the edited version to a temporary file
  • Rename or unlink the original file
  • Rename the temporary file with the original name
  • </bl> I was going to suggest the -i switch until I thought about it a bit more and realized that you probably don't want to always write if the editing is not necessary (and I don't know about the seekability of the <> input, either).
Re: editing a file
by malloc (Pilgrim) on May 31, 2001 at 19:40 UTC
    I think the best answer to your question can be found here: perl -i
    hope it helps!

    -malloc
Re: editing a file
by diarmuid (Beadle) on May 31, 2001 at 20:43 UTC
    yep there is
    perl -pi -e "s/something_regexp/something_else/g;" <filenames>
    at the command line will do the job Using the above with perl -pi.bak .... will put the original file into a backup copy called <orig>.bak