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

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

does the rename function delete the primary file regardless of whether the rename succeeds? i tested this and it seems as if this is true, is there any way to keep it from doing this or am i going to have to come up with some kind of workaround?
thanx for any help..

Replies are listed 'Best First'.
Re: rename
by lhoward (Vicar) on May 24, 2000 at 20:36 UTC
    The safe way to do this is to use the link/unlink commands. (pseudocode below)
    link file to new name/location
    if error
        handle error
    else
        unlink old filename/location
    
    note that this won't work if you are renaming across partitions on UNIX (but then neither will the rename command).
RE: rename
by mikfire (Deacon) on May 25, 2000 at 06:55 UTC
    For the platofrm generic way, I would direct your attention to the core module File::Copy.

    From the perldoc pages, I quote

      If possible, move() will simply rename the file.
      Otherwise, it copies the file to the new location and
      deletes the original.  If an error occurs during this
      copy-and-delete process, you may be left with a
      (possibly partial) copy of the file under the
      destination name.
    
    which seems to handle both the platform dependant issues as well as the the question jrsmith asked.

    Mik
    Mik Firestone ( perlus bigotus maximus )

Re: rename
by jrsmith (Pilgrim) on May 24, 2000 at 21:37 UTC
    just my luck, link is unsupported in win32
      I never use win32, but I imagine something like this would work (pseudo-code below):
      copy file from old name to new name if error handle error else delete old file
      Weird. Unlink() is implemented.