in reply to what is the best method to read and write in a file in perl

I agree with moritz's suggestion. However, if you really want to edit in place, you can use the -i option when running your script. I would suggest that you supply a backup extension to that so that perl will backup the file before editing it in place. Without that, perl will overwrite the file and if you made a mistake, you will have lost the original file.

Check out perlrun for more information about the -i flag.

  • Comment on Re: what is the best method to read and write in a file in perl

Replies are listed 'Best First'.
Re^2: what is the best method to read and write in a file in perl
by superfrink (Curate) on Sep 17, 2010 at 16:52 UTC
    Here is an example using -i. Notice that a new file is created with the same name. This isn't quite the same as editing the same file. You could have problems if there are multiple hard links to the file you are editing.

    [chad@desktop ~]$ ls -li asdf 2507085 -rw------- 1 chad chad 10 2010-09-17 10:44 asdf [chad@desktop ~]$ cat asdf 1 2 3 4 5 [chad@desktop ~]$ perl -p -i.bak -e 's/^2$/two/' asdf [chad@desktop ~]$ cat asdf 1 two 3 4 5 [chad@desktop ~]$ cat asdf.bak 1 2 3 4 5 [chad@desktop ~]$ ls -li asdf asdf.bak 2507203 -rw------- 1 chad chad 12 2010-09-17 10:46 asdf 2507085 -rw------- 1 chad chad 10 2010-09-17 10:44 asdf.bak [chad@desktop ~]$ perl -p -i -e 's/^2$/two/' asdf [chad@desktop ~]$ ls -li asdf asdf.bak 2507214 -rw------- 1 chad chad 12 2010-09-17 10:49 asdf 2507085 -rw------- 1 chad chad 10 2010-09-17 10:44 asdf.bak [chad@desktop ~]$
    Update: the sed command also has a -i flag.