Beefy Boxes and Bandwidth Generously Provided by pair Networks Frank
We don't bite newbies here... much
 
PerlMonks  

How can I keep the name of a file as .tmp until it process and is closed and after that it should be .html

by Anonymous Monk
on Apr 17, 2013 at 13:09 UTC ( #1029140=perlquestion: print w/ replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks, How can I keep the name of a working file as name.tmp until the work is going on and after when the file is closed rename it to name.html. Any suggestions? Thanks

Comment on How can I keep the name of a file as .tmp until it process and is closed and after that it should be .html
Re: How can I keep the name of a file as .tmp until it process and is closed and after that it should be .html
by choroba (Abbot) on Apr 17, 2013 at 13:10 UTC
    rename.
    لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: How can I keep the name of a file as .tmp until it process and is closed and after that it should be .html
by davido (Archbishop) on Apr 17, 2013 at 17:13 UTC

    File::Temp handles most of the things that you really don't want to deal with yourself (race conditions, portability, etc.), and cleans up after itself nicely. In your case, you would prefer to take over that clean-up process so that the temp file is renamed rather than unlinked as the script exits. Just make sure to do so with as much exception-safety and error safety as possible. Here's an example:

    use File::Temp; use File::Basename qw( basename ); use constant DEST_PATH => '/path/to/destination/'; use constant TEMP_PATH => '/tmp'; use constant TMP_TEMPLATE => 'prog_name.XXXX'; my $temp_fh = File::Temp->new( DIR => TEMP_PATH, TEMPLATE => TMP_TEMPLATE, UNLINK => 0 ); print "Temporary file created: ", $temp_fh->filename, "\n"; END{ my $new_filename = DEST_PATH . basename($temp_fh->filename) . '.html +'; rename $temp_fh->filename, $new_filename or do{ $temp_fh->unlink_on_destroy; die $temp_fh->filename, " couldn't be renamed: $!\n", "It will be unlinked instead."; }; print "Temp file was renamed to $new_filename\n"; }

    This method will cause a temp file to be created using a known filename with some random digits appended. Then upon termination it renames the file to a new path while at the same time adding .html to the filename. The random digits are preserved. This assures that if your script runs concurrently the multiple runs won't clobber a single temp or single html file.


    Dave

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (6)
As of 2014-04-21 02:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (489 votes), past polls