cpan beginner

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 $dir are scalar variables holding strings.
  • Regular expressions: We extract the directory part from the destination path with =~ m|^(.*)/|.
  • Context & Return values: move returns true on success; checking this prevents silent failures.
  • File tests: The -d operator checks if the directory exists.
  • TMTOWTDI: Perl allows many ways to ensure directories exist—here, a simple mkdir is 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 move will 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

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
Moving example.txt to archive/example.txt...
File moved successfully.
STDERR
(empty)

Was this helpful?

Related Questions