Recipe 9.3 Copying or Moving a File

9.3.1 Problem

You need to copy a file, but Perl has no built-in copy function.

9.3.2 Solution

Use the copy function from the standard File::Copy module:

use File::Copy;
copy($oldfile, $newfile);

You can do it by hand:

open(IN,  "<", $oldfile)                    or die "can't open $oldfile: $!";
open(OUT, ">", $newfile)                    or die "can't open $newfile: $!";

$blksize = (stat IN)[11] || 16384;          # preferred block size?
while (1) {
    $len = sysread IN, $buf, $blksize);
    if (!defined $len) {
        next if $! =~ /^Interrupted/;       # ^Z and fg on EINTR
        die "System read error: $!\n";
    last unless $len;

    $offset = 0;
    while ($len) {          # Handle partial writes.
        defined($written = syswrite OUT, $buf, $len, $offset)
            or die "System write error: $!\n";
        $len    -= $written;
        $offset += $written;


or you can call your system's copy program:

system("cp $oldfile $newfile");       # unix
system("copy $oldfile $newfile");     # dos, vms

9.3.3 Discussion

The File::Copy module provides copy and move functions. These are more convenient than resorting to low-level I/O calls and more portable than calling system. This version of move works across file-system boundaries; the standard Perl built-in rename (usually) does not.

use File::Copy;

copy("datafile.dat", "datafile.bak")
    or die "copy failed: $!";

move("datafile.dat", "")
    or die "move failed: $!";

Because these functions return only a simple success status, you can't easily tell which file prevented the copy or move from working. Copying the files manually lets you pinpoint which files didn't copy, but it fills your program with complex sysreads and syswrites.

9.3.4 See Also

Documentation for the standard File::Copy module (also in Chapter 32 of Programming Perl); the rename, read, and syswrite functions in perlfunc(1) and in Chapter 29 of Programming Perl