CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Text to file

 



emelin
stranger

Mar 5, 2001, 6:03 AM

Post #1 of 5 (420 views)
Text to file Can't Post

Okay, so I know this is in the FAQ, but I couldn't understand what I read! Could someone please tell me how to write text to the top of a file?

This is what I'm printing:
print FILE "@array";
print FILE '/something/';
I need the newest entries to be shown first!

thankful for help
emelin



japhy
Enthusiast

Mar 5, 2001, 6:32 AM

Post #2 of 5 (418 views)
Re: Text to file [In reply to] Can't Post

Let's say the file you want to edit is stored in $filename, and the new content is in the array @new_stuff. Then, you use the FAQ answer like this:


Code
{ 
local $^I = ''; # or '.bak', if you want a backup made
local @ARGV = $filename;
while (<>) {
print @new_stuff if $. == 1; # add the new content before line 1
print; # and print what was already there
}
}

And you're done.

Jeff "japhy" Pinyan -- accomplished hacker, teacher, lecturer, and author


emelin
stranger

Mar 5, 2001, 7:26 AM

Post #3 of 5 (416 views)
Re: Text to file [In reply to] Can't Post

Ok, thanks...

Noticed this only works if there already is something in the file. Is it possible to do this so you can start with an empty file?



japhy
Enthusiast

Mar 5, 2001, 7:37 AM

Post #4 of 5 (414 views)
Re: Text to file [In reply to] Can't Post

Sure. If the file doesn't exist yet, write to it, otherwise, use the code I showed you before:


Code
use Fcntl qw( O_CREAT O_EXCL O_WRONLY ); 

if (sysopen(FILE, $filename, O_CREAT | O_EXCL | O_WRONLY, 0644)) {
print FILE @new_stuff;
close FILE;
}
else {
local $^I = '';
local @ARGV = $filename;
while (<>) {
print @new_stuff if $. == 1;
print;
}
}

The way this works is the O_CREAT flag, in conjunction with the O_EXCL flag, means "create the file if it doesn't exist, and FAIL if the file DOES exist". So we either create the file and put stuff in it, or we know the file was already there, and so we use the in-place editing code.

Jeff "japhy" Pinyan -- accomplished hacker, teacher, lecturer, and author


emelin
stranger

Mar 6, 2001, 7:30 AM

Post #5 of 5 (407 views)
Re: Text to file [In reply to] Can't Post

Great. Thanks!


 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives