Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I write to the beginning of a file? 1

Status
Not open for further replies.

john99999

Instructor
Apr 29, 2005
73
0
0
US
This will write to the end of a file but how do I write to the beginning of the file without losing the contents already in that file?

open HTML, ">>c:/web/root/index.html";print HTML "Content-Type: text/html\n\n";
print HTML "<html><head></head><body>";
print HTML "<h2>Written by Perl!</h2>";
print HTML "</body></html>";close HTML;
 
Code:
#!/usr/bin/perl

chdir "/Users/duncancarr/Desktop";

open (EXISTING, "< existing_file.txt");
undef $/;
$existing = <EXISTING>;
$/ = "\n";
close EXISTING;

open (APPEND, "> existing_file.txt");

print APPEND <<HERE;
Content-Type: text/html

<html><head></head><body>
<h2>Written by Perl!</h2>
</body></html>"
$existing
HERE

close APPEND;


Kind Regards
Duncan
 
If you want to use a module, Tie::File is nice for this sort of thing.. in this example, changes to @array will result in an immediate change in your file:

Code:
use Tie::File;
tie @array, 'Tie::File', 'index.html' or die $!;
unshift @array, "now this is the first line";
 
Chazoid - nice...

I had no idea using Tie::File was as simple as that.

Mike

You cannot really appreciate Dilbert unless you've read it in the
original Klingon.

Want great answers to your Tek-Tips questions? Have a look at faq219-2884

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top