From:                   [EMAIL PROTECTED]
> This is the way I would do it, however my code has been subject to
> criticism more that once in the past :)
> 
> open (FILE, "<myfile.dat") or die;
> @file = <FILE>;
> close (FILE);
> $new_data = "This is my new line that I am going to put at the top\n";
> unshift (@file, $new_data); open (FILE, ">myfile.dat") or die; print
> FILE @file; close (FILE);

:-)

This is definitely a workable solution, there are just a few things 
to keep in mind.

1)This would mean that the whole file is read into the memory.
2)This would force Perl to search for end-of-lines and create an 
array.
3) You open the file in text mode in both cases. This may change the 
type of newlines in the file!

So it's fine for small files, but not so great for bigger ones.

If you want something more efficient you might try something like 
this:

open NEWFILE, '>', 'myfile.dat.tmp' 
  or die "Can't create myfile.dat.tmp: $^E\n";
print NEWFILE "the new stuff to put on top\n";
...

open OLDFILE, '<', 'myfile.dat'
  or die "Can't open the original file myfile.dat: $^E\n";
binmode(OLDFILE);
binmode(NEWFILE);
my $buff;
print NEWFILE $buff 
        while (read OLDFILE, $buff, 8*1024);
close NEWFILE;
close OLDFILE;
rename 'myfile.dat.tmp' => 'myfile.dat';

Jenda
===== [EMAIL PROTECTED] === http://Jenda.Krynicky.cz =====
When it comes to wine, women and song, wizards are allowed 
to get drunk and croon as much as they like.
        -- Terry Pratchett in Sourcery


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to