How to move file with File::Copy in Perl?
Question
How to move file with File::Copy in Perl?
Moving a file in Perl is most reliably done with the File::Copy module’s move function, which handles renaming or copying+deleting transparently. However, a common cause of failure is when the destination directory does not exist, as move does not create directories automatically.
How to move a file with File::Copy safely
Before calling move, ensure the target directory exists to avoid errors like "No such file or directory". You can create directories using mkdir and check its success. This approach keeps your script robust and portable.
use strict;
use warnings;
use File::Copy;
my $source = 'example.txt';
my $destination = 'archive/example.txt';
print "Moving $source to $destination...\n";
# Extract directory path from destination
my ($dir) = $destination =~ m|^(.*)/|;
# Create directory if it does not exist
unless (-d $dir) {
mkdir $dir or die "Failed to create directory '$dir': $!\n";
}
# Attempt to move the file
if (move($source, $destination)) {
print "File moved successfully.\n";
} else {
die "Failed to move file: $!\n";
}
Perl-specific concepts illustrated
- Sigils:
$source,$destination, and$dirare scalar variables holding strings. - Regular expressions: We extract the directory part from the destination path with
=~ m|^(.*)/|. - Context & Return values:
movereturns true on success; checking this prevents silent failures. - File tests: The
-doperator checks if the directory exists. - TMTOWTDI: Perl allows many ways to ensure directories exist—here, a simple
mkdiris sufficient.
Common pitfalls to avoid
- Trying to move files to non-existent directories without creating them.
- Not checking the return value of
mkdir, which can fail due to permissions. - Using relative vs absolute paths inconsistently.
- Assuming
movewill create intermediate folders.
By ensuring the destination folder exists first, this example will run successfully in any typical environment without external dependencies or file system access issues (assuming the source file exists).
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 28ms
Moving example.txt to archive/example.txt...
File moved successfully.
(empty)Was this helpful?
Related Questions
- How to use File::Slurp to read entire file into variable in Perl?
- How to get file modification time with Path::Tiny in Perl?
- How to use Path::Tiny touch to create empty file in Perl?
- How to use List::Util reduce for custom aggregation in Perl?
- How to compare two DateTime objects in Perl?
- How to use DateTime::Duration for time periods in Perl?