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

Hello, Am trying to read and write into a same file. I used the following method for opening a file to read and write.
open '+<', '<file.txt';
Assume that the file has the following content,
1 2 3 4 5
I want to make it to this way
1 two hi hello 3 4 5
I followed this way,
open FH, '+<file.txt'; while (<FH>) { print $_; if ( /^2/ ) { print FH "two\nhi hello\n"; } }
but which removes all the following lines and makes the file like this,
1 2 two hi hello
What is the issue ? So i would like to know what is the best method to read and write in to the same file.

Replies are listed 'Best First'.
Re: what is the best method to read and write in a file in perl
by moritz (Cardinal) on Sep 17, 2010 at 14:04 UTC
    The easist way is not to read from and write to the same file at all. Instead open a second file for writing, copy the parts that you don't want to change, and in the end remove the first file, and move the second file to the previous location of the first file.
    Perl 6 - links to (nearly) everything that is Perl 6.
Re: what is the best method to read and write in a file in perl
by BrowserUk (Patriarch) on Sep 17, 2010 at 15:34 UTC
    What is the issue ?

    The issue is that you're in overwrite mode not insert mode. :)

    This may make things clearer. (~ represent newlines).:

    1~2~3~4~5~ ## Old contents 1~2~two~hi hello~ ## New contents.

    I'm guessing that it was your intent to replace the '2' with 'two', but as you'd just read the '2' from the file, the file pointer was already pointing at the '3', so that where it started writing.

    And because what you wrote was longer than what is there, you overwrote everything beyond the point where you started.

    To understand what you would need to do in order to achieve what you set out to achieve, put you console into overwrite mode, type the original contents (on one line with '~'s as above. Then back up to the point you want to replace and start typing. (Without setting insert mode on, because files don't have an insert mode.)

    Then forget the idea and do as moritz suggested.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: what is the best method to read and write in a file in perl
by dasgar (Priest) on Sep 17, 2010 at 14:39 UTC

    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.

      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.
Re: what is the best method to read and write in a file in perl
by pemungkah (Priest) on Sep 17, 2010 at 18:25 UTC
    I find that the absolute easiest way to handle file editing (if the file's not too big) is to use Tie::File. This lets you treat the file as if it were an array; if you case you could then just splice in the items you want.
Re: what is the best method to read and write in a file in perl
by jakeease (Friar) on Sep 18, 2010 at 01:30 UTC

    Your original code as BrowserUK said is writing the replacement after moving past the 2. And moritz is right that reading from the file and writing to a temp is better most of the time. If you have forgo the the temp file, something like the following could work:

    open FH, '+<afile'; $temp = ''; while (<FH>) { s/2/two\nhi hello/; $temp .= $_; } seek(FH, 0, 0); print FH $temp; truncate(FH, tell(FH)); close(FH);

    this deals with the '2' when it finds it instead of after passing it. As long as your file isn't huge, like a logfile, this isn't too much of a memory hog. If I'm going to do it in memory, I do something more like the following than all that "IOish" stuff above.

    sub slurp { my $file = shift; open my $fh, '<', $file or return undef; local $/ unless wantarray; return <$fh> if defined wantarray; } sub jot { my $notepad = shift; open my $fh, ">", $notepad or die $!; print $fh @_; } my $temp = slurp 'file.txt'; $temp =~ s/2/two\nhi hello/; jot 'file.txt', $temp;

    The lexically scoped filehandle, $fh, goes out of scope when slurp returns and $fh is automatically closed before jot begins. slurp will return an array of lines if called with an array, or a string containing the whole file if called with a scalar as I did.