Jenda Krynicky wrote:
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';
You *can* of course modify the file in-place (if the OS supports it.)
my $file = 'myfile.dat';
my $text = "the new stuff to put on top\n";
open my $IN, '+<', $file or die "Cannot open '$file' for input: $!";
binmode $IN;
open my $OUT, '+<', $file or die "Cannot open '$file' for output: $!";
binmode $OUT;
$/ = \length $text;
while ( my $buff = <$IN> ) {
print $OUT $text;
$text = $buff;
print $OUT $text if eof $IN;
}
John
--
use Perl;
program
fulfillment
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>