开发者

What is the Perl equivalent of the 'mv' system command?

开发者 https://www.devze.com 2023-01-06 10:44 出处:网络
I have the below \"system command\" for moving the file.Is it good to use File::Move command or the use the below one.In case if File::Move i开发者_运维知识库s better, how can I use it?

I have the below "system command" for moving the file. Is it good to use File::Move command or the use the below one. In case if File::Move i开发者_运维知识库s better, how can I use it?

system("mv $LOGPATH/test/work/LOGFILE  $LOGPATH/test/done/$LOGFILE") == 0
  or WriteLog(ERROR, "mv command Failed $LOGPATH/test/work/$LOGFILE  status was $?");


The function you are looking for is in File::Copy:

use File::Copy 'move';
move $x, $y or WriteLog ("move $x, $y failed: $!");

File::Copy is part of the standard distribution of Perl itself.

You can of course use a system ("mv ...") command to do the same thing. The advantages of File::Copy are:

  • It will work across different operating systems, which may be necessary if you're writing something for other people to use;
  • It doesn't expose you to security holes due to passing data to the shell, or portability bugs because the filepath has meta characters and spaces in it like /Library/Application Support/Hi I'm On A Mac/;
  • It is faster: see Schwern's paste. The cost of system swamps everything else. File::Copy::move and rename have about the same cost, so you may as well use the safer move which works across filesystems.


Here's one more thing to add to the mix -- if you're moving the file within the same device (that is, there is no need to move the file contents, only update its directory entry), you can simply use the builtin function rename:

rename OLDNAME,NEWNAME

Changes the name of a file; an existing file NEWNAME will be clobbered. Returns true for success, false otherwise.

Behavior of this function varies wildly depending on your system implementation. For example, it will usually not work across file system boundaries, even though the system mv command sometimes compensates for this. Other restrictions include whether it works on directories, open files, or pre- existing files. Check perlport and either the rename(2) manpage or equivalent system documentation for details.

For a platform independent "move" function look at the File::Copy module.


To add to Kinopiko's otherwise excellent answer, one of the two main reasons to use File::Copy over the system mv command - aside from not-always-relevant-but-still-meaningful portability concern he noted - is the fact that calling a system command forks off at least one child process (and if you do any re-directs, two of them - mv and shell). This wastes a lot of system resources compared to File::Copy.

0

精彩评论

暂无评论...
验证码 换一张
取 消