file-io intermediate

How to copy a file in Perl?

Question

How to copy a file in Perl?

How to Copy a File in Perl

Copying a file in Perl is commonly done using the core module File::Copy, which provides a straightforward and reliable copy function. However, to successfully copy a file, the source file must exist before the copy operation; otherwise, you will get errors like No such file or directory.

This example demonstrates how to safely copy a file by first creating a sample source file in-memory. This approach avoids external dependencies, works perfectly in a sandbox, and shows the complete workflow.

Key Points About Perl's File Copying

  • File::Copy::copy returns true on success, false on failure.
  • Source and destination file names are scalars, denoted by $ (scalar sigil).
  • Always check the return value of copy and I/O operations to handle errors gracefully.
  • Use binmode on filehandles if copying binary files (important on Windows).
  • Perl emphasizes “There’s more than one way to do it” (TMTOWTDI), but File::Copy is usually simplest.

Runnable Example: Copying a File Successfully


use strict;
use warnings;
use File::Copy;

my $source = 'example_source.txt';
my $destination = 'example_copy.txt';

# Create a source file to copy
open my $src_fh, '>', $source or die "Can't create $source: $!";
print $src_fh "Sample content for copying.\n";
close $src_fh;

# Copy the file
if (copy($source, $destination)) {
    print "Successfully copied '$source' to '$destination'.\n";
} else {
    die "Copy failed: $!";
}

# Read and print the destination file to verify
open my $dst_fh, '<', $destination or die "Can't open $destination: $!";
print "Contents of '$destination':\n";
print while <$dst_fh>;
close $dst_fh;

This script:

  • Creates example_source.txt with sample text.
  • Copies it to example_copy.txt using File::Copy::copy.
  • Prints confirmation or dies on error.
  • Reads back the destination file and prints its contents to STDOUT.

Common Pitfalls and Notes

  • Missing source file: If the source file does not exist, copy will fail with an error.
  • Binary files: Use binmode on filehandles when copying binary files manually.
  • Permissions: The copy function preserves file content but not extended metadata like timestamps.
  • Filehandles and buffers: When copying manually, buffer sizes and error checking are important to avoid silent data loss.

Using File::Copy is the recommended way to copy files in Perl for clarity, safety, and portability. Just ensure the source file exists beforehand to avoid runtime errors.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 17ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
Successfully copied 'example_source.txt' to 'example_copy.txt'.
Contents of 'example_copy.txt':
Sample content for copying.
STDERR
(empty)

Was this helpful?

Related Questions