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

Hi I have the following question: I am running a program and writing some information in a file...In the end I want to write something on the first line and displace the information I have already written by a line How do I do that?

Replies are listed 'Best First'.
Re: Writing in files
by roboticus (Chancellor) on Feb 06, 2010 at 20:10 UTC

    nicholaspr:

    If you mean move the rest of the file down a couple lines, you can't really do it. Instead you create a new file, write the information to it, and then copy the rest of the original file into it. If you don't mind extra space at the beginning of your file, you could put a block of spaces (or other filler) character at the beginning of your file when you initially create it, and when you're done, you can rewind (seek) to the start of the file and write the new information over the filler region. That would save you (or some other code) from doing the copy.

    ...roboticus

Re: Writing in files
by toolic (Bishop) on Feb 06, 2010 at 20:15 UTC
    One way to do it is to use Tie::File to treat your file as an array, then just prepend a new first line using unshift:
    use strict; use warnings; use Tie::File; tie my @array, 'Tie::File', 'file.txt' or die $!; unshift @array, 'new first line'; untie @array;