in reply to What's the best way to avoid name collisions when creating files?

Well... there is always the old date,time and pid combination... that works fine as long as the script doesn't handle multiple messages in a loop. Of course, if it does handle messages in a loop it is easy to tell what the last name you used was and increment a counter if it is the same.

There is always file locking with something like flock...

And I believe you can also use sysopen to create files if they aren't there and error if they are, but not 100% sure on that... something with O_CREAT and O_EXCL maybe...

                - Ant
                - Some of my best work - (1 2 3)

  • Comment on Re: What's the best way to avoid name collisions when creating files?

Replies are listed 'Best First'.
Re^2: What's the best way to avoid name collisions when creating files?
by bmann (Priest) on May 02, 2005 at 20:31 UTC
    And I believe you can also use sysopen to create files if they aren't there and error if they are,

    You can, and O_CREAT and O_EXCL are exactly the flags the OP needs.

    C:\t>set DIRCMD=/b C:\t>dir newfile File Not Found C:\t>perl -MFcntl -e "sysopen F, 'newfile', O_EXCL | O_CREAT or die" C:\t>dir newfile newfile C:\t>perl -MFcntl -e "sysopen F, 'newfile', O_EXCL | O_CREAT or die" Died at -e line 1.
Re^2: What's the best way to avoid name collisions when creating files?
by osunderdog (Deacon) on May 02, 2005 at 21:11 UTC

    There's a cavat to flock though. It doesn't work across the network . If you know that you're always going to use the local file system, then great. However if you move to a NAS, flock may stop working.

    I ran into this with DBD::CSV. DBD::CSV will use flock under the hood to ensure that it has exclusive access to the file it is reading/writing. However if the file is on a NAS (Network Area Storage) and accessed with NFS, then DBD::CSV will fail to open the file.

    Soon to be unemployed!
Re^2: What's the best way to avoid name collisions when creating files?
by doom (Deacon) on May 03, 2005 at 21:20 UTC
    Well... there is always the old date,time and pid combination... that works fine as long as the script doesn't handle multiple messages in a loop.
    Several people here have mentioned using the "pid", and I just wanted to make sure it's understood that the "$$" special variable always contains the process id. It's a very common idiom to name a temp file something like "/tmp/my_scripts_temp.$$", so that if you've got two instances of the same script running on the same machine at the same time they won't stomp on each other.

    Also, I've been known to do things like this:

    my $filename = "~/tmp/temp.$$"; while (-e $filename) { $filename .= '.' . chr(int(rand(25)) + 65); }
    though this, of course, presumes that you don't have to worry too much about race conditions.