How to remove, copy or rename a file with Perl
Many people who come from the world of system administration and Unix or Linux scripting, will try to keep using the regular unix commands of rm, cp and mv for these operations. Calling them either with back-tick or with system, even when writing Perl scripts.
That works on their current platform, but that gives up one of the key benefits Perl brought to the world of Unix system administration.
Let's see how can we execute these operations with Perl in a platform-independent way, and without shelling out.
The name of the respective built-in function in perl is unlink.
It removes one or more files from the file system. It is similar to the rm command in Unix or the del command in Windows.
unlink $file; unlink @files;
It uses $_, the default variable of Perl if no parameter is given.
For full documentation see perldoc -f unlink.
Renames or moves a file. Similar to the mv command in Unix and rename command in DOS/Windows.
rename $old_name, $new_name;
As this does not always work across file systems the recommended alternative is the move function of the File::Copy module:
use File::Copy qw(move); move $old_name, $new_name;
There is no built-in copy function in core perl. The standard way to copy a file is to use the copy function of File::Copy.
use File::Copy qw(copy); copy $old_file, $new_file;
This is similar to the cp command in Unix and the copy command in Windows.
For documentation visit perldoc File::Copy.