in reply to writing to top of a file

example code would be ...

open (FH, "<filename.txt") || die "could not open file: $!"; @ODB = <FH>; close (FH); $newline = "The new line of text to go at the top of the file"; open (NFH, ">filename.txt") || die "could not open file 2: $!"; print NFH "$newline" . "\n"; foreach $line (@ODB) { print NFH "$line"; } close (NFH);

There are so many different ways to do it ... it is crazy to try and put them all here. The example above is ok, but if the file is very large, you might want to use join the data.

HTH,

- f o o g o d

--- ruining the bell curve for everyone else ---

Replies are listed 'Best First'.
Re: Re: writing to top of a file
by abstracts (Hermit) on Aug 06, 2001 at 22:37 UTC
    Hello

    You said: The example above is ok, but if the file is very large, you might want to use join the data.

    Joining the data will not eleminate the problem, it will only delay it (and not by much for that matter). If the file is very large, use:

    use File::Temp qw/tempfile/; open $FIN, "<$file1" or die .... my ($fh, $fname) = tempfile(); print $fh "FIRST LINE\n"; print $fh $_ while <$FIN>; close $FIN; close $fh; rename $fname, $file1;
    Code to check success of operations is not included for readability

    Aziz,,,

    Update: Thanks runrig for the comment. The point is the same, don't read all data into memory when moving data from file to file.

      Just use File::Copy (more efficient than reading/writing one line at a time):
      use File::Temp qw/tempfile/; use File::Copy; my ($fh, $fname) = tempfile(); syswrite $fh, "FIRST LINE\n"; copy($file1, $fh) or die "Error copying: $!"; close $fh;
      rename $fname, $file1;