cpan beginner

How to copy file using File::Copy in Perl?

Question

How to copy file using File::Copy in Perl?

Copying Files in Perl Using File::Copy (with a Sandbox-Friendly Example)

The File::Copy module is the standard way to copy files in Perl and is part of the core distribution. It provides a simple copy function to duplicate the contents of one file to another. However, when running code in a restricted environment or sandbox without access to actual files (like input.txt), you’ll encounter errors.

To demonstrate copying with File::Copy in a sandbox, we can create a temporary file in-memory (using a scalar variable) or generate a file dynamically first, then copy it. Below is a fully runnable example that:

  • Creates a test file input.txt with sample content
  • Copies it to output.txt using copy
  • Reads and prints the copied file content to confirm success

Runnable Perl Example

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

my $source = 'input.txt';
my $dest   = 'output.txt';

# Create a sample source file first for demonstration
open my $fh, '>', $source or die "Cannot create $source: $!";
print $fh "Hello, Perl File::Copy example.\n";
close $fh;

# Attempt to copy the file
if (copy($source, $dest)) {
    print "File copied successfully from $source to $dest.\n";

    # Verify copied content by reading output file
    open my $fh_out, '<', $dest or die "Cannot open $dest: $!";
    while (<$fh_out>) {
        print "Copied content: $_";
    }
    close $fh_out;
} else {
    die "Failed to copy $source to $dest: $!\n";
}

# Clean up created files (optional)
unlink $source;
unlink $dest;

Explanation

  • use File::Copy; imports the copy function for file copying.
  • We create the input.txt file dynamically since a sandbox likely has no pre-existing files.
  • copy($source, $dest) returns true if successful; otherwise false and sets $! with the error.
  • After copying, reading output.txt verifies the operation by printing the copied content.
  • unlink cleans up files to restore the original sandbox state.

Perl Concepts Highlighted

  • Sigils: $ for scalars like filenames, @ and % are for arrays and hashes respectively.
  • Filehandles: Standard I/O handles opened via open to read/write files.
  • Context: copy returns boolean success/failure.
  • Error Handling: Use die and check $! for system errors during I/O operations.

Common Pitfalls

  • Trying to copy a file that doesn’t exist causes "No such file or directory" error, as seen in your sandbox failure.
  • copy works on filenames, not filehandles directly.
  • Be aware that copy overwrites destination files without warning.
  • Running in restricted environments means you might need to create or mock files first.

Summary

Using File::Copy in Perl is straightforward but requires that source files exist. This example works in sandboxed environments by first creating a source file, then copying it. The approach is portable and available in all modern Perl versions without additional modules.

Verified Code

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

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
File copied successfully from input.txt to output.txt.
Copied content: Hello, Perl File::Copy example.
STDERR
(empty)

Was this helpful?

Related Questions