What is the best way of writing the some content to the beginning and end of a File in Perl
Hi Krish,
The following code is the most simple example I can think of.
#!/usr/local/bin/perl
open (MYFILE, '>>data.txt');
print MYFILE "Bob\n";
close (MYFILE);
The '>>' tells the open function that you want to edit file by placing characters onto the end of it.
Replace this with '>' to replace the content instead.
To place the content at the beginning of the file - I would suggesting reading in the file, manually placing the content at the begging of the char array, and then writing to the file with '>'
Hope that helps,
twd20
Appending is trivial:
open my $fh, '>>', 'some.file' or die "Cannot open file for append: $!\n";
print $fh $some_content;
close $fh;
On the other hand, adding something in the beginning (or in the middle) is very complicated.
One way to do it:
use File::Temp qw/ tempfile /;
use File::Copy;
open my $in, '<', 'some.file' or die "Cannot open file for reading: $!\n";
my ($out, $temp_file_name) = tempfile();
print $out $some_content;
my $l;
print $out $l while defined( $l = <$in> );
close $in;
close $out;
move( $temp_file_name, 'some.file' );
Use the Tie::File module and it can be done easily although it may not be the most efficient way. You can edit a file just as if it is a perl array, so to add a line to the beginning you would use unshift() and add a line to the end you can use push(). The modules documentation is pretty clear on how to use it.