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

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

I have a file I am using on my website, and I want to go in, at a specified spot, and change|add info to that spot. Is there an easier way besides writing to a temp file, then renaming the temp file over the old file? Thanks
  • Comment on How do you write to the middle of a file?

Replies are listed 'Best First'.
Re: How do you write to the middle of a file?
by devslashneil (Friar) on Jun 13, 2003 at 00:54 UTC
    #!/usr/bin/perl use Tie::File; my $filename = 'foo.dat'; tie @array, 'Tie::File', $filename or die "Cannot open $filename\n"; @array[5] = "Hello, World!\n";
Re: How do you write to the middle of a file?
by Anonymous Monk on Feb 11, 2000 at 23:06 UTC
    Such is the evil of the standard (read UNIX) file model. One solution is as follows:
    $flen = -s $file; # file length in bytes $from = 42; # insertion point open FILE, '+<the/file.ext' or die "Couldn't open file: $!"; read FILE, $buf, ($flen - $from), $from; seek FILE, $from, 0; print FILE 'blahblahblah', $buf;