in reply to Re^2: Copying files between directories. How can I improve this code.
in thread Copying files between directories. How can I improve this code.

Ok, here is a version with a little "magic" done.

#!/usr/local/bin/perl -W # force taint checks, and print warnings use strict; # install all three strictures use File::Copy; use File::Find; my $path = "C:/Perl/eg"; #define full path to source folder my $newpath = "c:/Delme"; #define path to new folder $| = 1; # force auto flush of output buffer chdir($path) || die "cannot move to $path"; find (\&doCopy, $path); #Recursively search $path for files to copy sub doCopy { return if ! -f $File::Find::name; my $subTree = substr $File::Find::name, 1 + length $path; my $destFile = "$newpath/$subTree"; print "\$destFile = $destFile\n"; #copy ($_, $destFile) or print "File $_ cannot be copied. $!\n"; }

Prints:

$destFile = c:/Delme/example.pl $destFile = c:/Delme/Readme.txt $destFile = c:/Delme/aspSamples/ado1.asp $destFile = c:/Delme/aspSamples/ado10.asp $destFile = c:/Delme/aspSamples/ado11.asp $destFile = c:/Delme/aspSamples/ado12.asp $destFile = c:/Delme/aspSamples/ado13.asp $destFile = c:/Delme/aspSamples/ado14.asp $destFile = c:/Delme/aspSamples/ado15.asp ...

Note that you needn't interpolate variables into strings to pass them as parameters, just pass the variable: copy ($_, $destFile) for example.


DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^4: Copying files between directories. How can I improve this code.
by richill (Monk) on Apr 22, 2006 at 08:48 UTC

    Thats more then I expected, Thankyou.

    my $subTree = substr $File::Find::name, 1 + length $path;

    I see this string declares subtree and initialises it as the name of the file currently in Find. I'm not sure what this does 1 + length $path

    Does it change the value of $path to 1$path for the first folder.

    Actually I know, it uses substr to pullout the part of $File::Find::name after the last /.

      substr takes up to four parameters. A string, a start offset, a length and a replacement string. In this case, given a string and an offset, it returns the contents of the string from the offset to the end of the string. The statement is slicing the original path off the front of the actual path to the file and retaining the subdirectory path (if any).

      Take a look at the code and at the output and you should be able to infer what is going on.


      DWIM is Perl's answer to Gödel