Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Replacing the last line in a file

by steveAZ98 (Monk)
on Jun 18, 2001 at 23:50 UTC ( [id://89423]=perlquestion: print w/replies, xml ) Need Help??

steveAZ98 has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to figure out the best way to replace the last line in a script every time the script is run. I know I can rewrite the file with the new last line each time, but I would like a more elegant way. Any suggestions?
Thanks!
#!/usr/bin/perl -w use strict; # do stuff __DATA__ record to replace

Replies are listed 'Best First'.
Re: Replacing the last line in a file
by AidanLee (Chaplain) on Jun 19, 2001 at 00:15 UTC
    Are you sure you wouldn't rather use an external data file? Self-modifying scripts are not for the faint of heart. I've heard more than once on this site that it's generally a Bad Idea (TM). If you're just using the __DATA__ handle at the end of the script, you might as well use an external file.
Re: Replacing the last line in a file
by wog (Curate) on Jun 19, 2001 at 00:12 UTC
    Well, as long as you can be sure its the last line, you can find out where the last line is and use truncate, and then append the new last line. I have an example here where I just replace the whole __DATA__ portion:

    #!/usr/bin/perl -w use strict; my $new = "new text here!\n"; my $data_pos = tell DATA; open SELF, "+<$0" or die "open $0: $!\n"; truncate SELF, $data_pos or die "truncate: $!\n"; seek SELF, 0, 2 or die "seek: $!\n"; # append now. print SELF "$new" or die "print: $!\n"; # just in case close SELF or die "while closing $0: $!\n"; __DATA__ this is the stuff to replace

    Be aware that this has a race condition if two copies of the script are run at once. The race condition can be eliminated by adding an flock after open as long as it can be gaurenteed that the script (before the __DATA__) will not be modified while it runs.

    update: (more) minor typos fixed, die check added, (more recently) rephrased to actually explain algorithm.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://89423]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (5)
As of 2024-04-24 08:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found