1. Perl
  2. File operation
  3. here

Copy the file

To copy a file, use the copy function of File::Copy module. If it succeeds, it returns true, and if it fails, it returns false. If the copy function fails, the details of the error are stored in $!.

use File::Copy 'copy';
copy $file, $copy_name;

You can also copy the file into a directory.

use File::Copy 'copy';
copy $file, $dir;

Example

This is an example to copy a file.

use strict;
use warnings;
use Fcntl;
use File::Copy 'copy';

# Copy the file.
my $file = "example_20080521_$$. txt";
my $dir = "dir_20080521_ $$";

# Prepare files and directories
sysopen(my $fh, $file, O_WRONLY | O_CREAT | O_EXCL)
  or die "Unable to create $file .:$!";
close $fh;
print "Preparation:'$file' has been created.\n";

mkdir $dir
  or die "Unable to create $dir.:$!";
print "Preparation:'$dir' has been created.\n\n";

print "1. Copy the file.\n";
my $copy_name = "$file.copy";
if (copy $file, $copy_name) {
  print "$file has been copied to $copy_name.\n\n";
}
else {
  warn "Unable to copy $file to $copy_name. $!";
}

print "2. Copy the file to a directory.\n";
if (copy $file, $dir) {
  print "$file has been copied to $dir.\n\n";
}
else {
  warn "Unable to copy $file to $dir .:$!";
}

(Reference) sysopen function, Fcntl

Related Informatrion