tags:

views:

185

answers:

5

What is the best way of writing the some content to the beginning and end of a File in Perl

+8  A: 

This is covered by the FAQ

David Dorward
+1  A: 

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

twd20
+2  A: 

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' );
depesz
I would tend to make a backup of the original always - just in case I screw something up in the script. Also, will `print out $l while my $l = <$in>;` work?
Telemachus
As for backup - you can of course. as for the while - sorry, no. I fixed it, and added proper check with defined().
depesz
+1  A: 

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.

+1  A: 

Are you looking for a templating system?

ysth