in reply to Safe Temp Files

While "safe" might be in the eye of the beholder (and I know I'm going to draw comments on that statement) reliable is another matter.

First off, I try and write my code in such a way that I don't need temporary files. Leaving surds all over the disk is somthing I don't like to do and I'll go to great lengths to avoid it. My biggest issue with temporary files is they tend to become "permanent" files because quite often either because of oversight on the behalf of the programmer or because Something Bad Happened™ to the process during its lifecycle the temporary files don't get cleaned up after.

Having asserted that premise I'll go on to say that in the rare occasion that I need a temporary file I tend to use one of two methods.

Name it by PID

The most common way I enact a temporary file is to create a filename that is related to both the reason I'm creating it and the process id for example:

my $unsortedUsersFilename="munger-unsortedusers.$$.txt"; | etc
In this example, munger is the name of the script doing the work, unsertedusers refers to the fact that it will contain a set of unsorted users (hey! work with me here!) and the $$ is the *nix PID of the script that is creating it.

During debugging sessions I may well leave off the step of removing the temp file so I can examine this file and know what was going on if the code doesn't work the way I expected it to.

The don't reinvent the wheel method

I like using File::Temp once my script has been debugged and I no longer care about the name of the being generated. While the module does provide a templating function for filenames, the names are still random. The biggest reason I like this module is it is platform portable. While 99.999% of my scripting is done on the *nix family of OSs every once in a while I end up writing something on the Evil Empire® platform and so I like things that I write to be portable.

Hope this at least provides you with food for thought.


Peter L. Berghold -- Unix Professional
Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg

Replies are listed 'Best First'.
Re^2: Safe Temp Files
by cdarke (Prior) on Dec 04, 2006 at 17:28 UTC
    Using a PID is easy and commonly used on UNIX, but it might bite you if you port that to Windows if you want the file to survive after the program. On UNIX the PIDs cycle around, and it will be "a long time" before your PID gets reused, but on Windows a PID can get reused by the next process that starts.
          Windows a PID can get reused by the next process that starts.

      Yes, I am aware of that limitation on 'doze. Fortunately for me I don't do a lot of coding on that platform and for the occasion I stick with File::Temp and write the filename to a log file for perusal/retrieval later on.


      Peter L. Berghold -- Unix Professional
      Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg