http://www.perlmonks.org?node_id=860526


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

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.