perlrenamefile-rename

File::Copy vs. rename


There is a Perl utility rename (perldoc -f rename), which is, if I understood correctly, a wrapper around the rename system call (man rename -> System Calls Manual: RENAME(2)), and there are many versions of it: https://unix.stackexchange.com/q/730894

At the same time, its man page, perldoc -f rename, which is already mentioned above, implicitly recommends, if I understood correctly, to rename files using File::Copy's move instead.

Is my understanding correct? That is, is it correct that it is best to use move over rename? (Because: a) it is more robust, according to perldoc -f rename, b) there is no mess with different versions.)

And if this is true, then why Perl Cookbook, in the section Renaming Files, doesn't mention move, and instead mentions rename only? Edit: What I actually mean here in the second part of the qurstion is: "Since we already have move, what's the point to have rename at all?"


Solution

  • Yes, the File::Copy module is more versatile and more dependable than rename command.

    The textbook talks about rename command because it is actually part of the language and if you have perl binary, you have access to rename command. The module is an extra, very popular and well known, but still an extra. To use it you must use it first. Even though it is installed by default, but to use in a script, you must add use File::Copy; line.

    The rename do have issues, and they are listed in the documentation. But just look at that list. How often do you need to move files from one FS to another? How often do you need to rename open files?

    In practice, while I do know about File::Copy I never had a real need for it. All my real-life interaction with that module was a maintenance of some one else's code. Granted, that my usual need for file renaming does not go beyond rotating logs/backups. Or create temp-file, delete original data file, rename temp to original. Anything fancier is usually a one-time task which does not justify writing a script.

    So, if your renaming needs are simple enough for rename command - go for it. If you suspect that rename will fail in your environment - use File::Copy.