http://www.perlmonks.org?node_id=368117


in reply to Re^2: A DWIM too far?
in thread A DWIM too far?

As is, the behaviour makes it impossible to safely rename a file.

That depends on your definition of "safely". The other possible default (not renaming if the target file exists), also prevents "safely" renaming a file. Because that will prevent the to-be-renamed file to be renamed. So that's also "unsafe".

You should also consider what should happen in the following situation:

$ touch file $ ln -s target link $ rename file link
Rename or not?

Note that if you want to do a "safe" rename, you can do so, although it involves a copy:

my ($f1, $f2); if (sysopen $f1, "new", O_WRONLY | O_CREAT | O_EXCL) { open $f2 => "old" or die; print $f1 <$fh2>; close $f1 or die; unlink "old" or die; }
You can test existance before issuing the rename, but in any multi-tasking environment there is always the possibility that the target file will be created between the test for existance and the rename.
Frankly, I don't get your point. What are you trying to say here? That the rename is making you lose data? That I disagree with. Suppose you are multi-tasking, one threads wants to create a file "new", and another thread wants to move "old" to "new", but you want to end up with both the data that is in "old", and with the data that would be placed in "new" by the other thread. Suppose you would have a 'rename' that doesn't rename if there is already a "new" file. Does that win you anything? Not if the renaming process thread goes first. Then "old" will be renamed to "new", and then wiped out by the other thread that's creating "new". Rename is not to blame in this scenario - the programmer is to blame by not syncronizing two threads that modify the same resource.
This rates up there with non-exlusive-opens-by-default and cooperative locking as remnant bahaviours of a bygone era that should have been superceded long ago.
Well, you can always change your system calls. Oh, wait, you can't.

Abigail