FAQ 5.5 How can I copy a file?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
This is an excerpt from the latest version perlfaq5.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .


5.5: How can I copy a file?

    (contributed by brian d foy)

    Use the File::Copy module. It comes with Perl and can do a true copy
    across file systems, and it does its magic in a portable fashion.

            use File::Copy;

            copy( $original, $new_copy ) or die "Copy failed: $!";

    If you can't use File::Copy, you'll have to do the work yourself: open
    the original file, open the destination file, then print to the
    destination file as you read the original.


The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in

Re: FAQ 5.5 How can I copy a file?

Quoted text here. Click to load it

What is the advantage of using this over using system("cp $original
$new_copy"); (or system("copy $original $new_copy"); on windows)? Is
it faster or is it just "perlish"? Or am I missing something obvious?

Bill H

PS When did Google Groups drop the captcha?

Re: FAQ 5.5 How can I copy a file?

Quoted text here. Click to load it

system() isn't portable.
File::Copy also avoids forking external processes, although the time
savings are probably pretty irrelevant given the nature of the


Re: FAQ 5.5 How can I copy a file?

Quoted text here. Click to load it

I think you just answered your question: The advantage is that you can
just write

    copy( $original, $new_copy )

instead of

    if (os_is_some_kind_of_unix()) {
    system("cp", $original, $new_copy);
    } elsif (os_is_windows()) {
    system("copy", $original, $new_copy);
    } else {

and wonder how you can write sub os_is_some_kind_of_unix.

(and you won't make stupid mistakes like system("cp $original
$new_copy"). which won't work if either $original or $new_copy contains
any of a large number of "dangerous" characters)

OTOH, when you use a system-specific tool like "cp", you can do
system-specific things, like preserve permissions or timestamps.

Quoted text here. Click to load it

It is probably faster for small files. It also is more robust (even if
the system has a "cp" command, it may not be in your path).

Quoted text here. Click to load it

That, too.


Site Timeline