Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

With the following code: I can't seem to move every thing recursively, Any ideas?
use File::Copy; use strict; if(-d $workspace) { opendir(WorkSpace, "$workspace") || die "Error: Can't open $workspace directory: $!"; @WorkSpace = readdir(WorkSpace); closedir WorkSpace; my $backup_dir = $workspace; $backup_dir = join("", "$workspace", "-backup"); if (-d $backup_dir) { system "del $backup_dir"; } else { mkpath("$backup_dir") } foreach my $file (@WorkSpace) { move("$workspace\\$file", "$backup_dir\\$file"); } }

Replies are listed 'Best First'.
Re: moving directories recursively
by vladb (Vicar) on Jun 03, 2002 at 15:07 UTC
    By looking at your code, me thinks it will only copy the immediate contents of the $workspace directory. You simply read ('first' level) list of files/directories inside the directory (with the readdir() method) but never actually 'recurse' through sub-directories. I suggest you use the File::Find module and it's wanted() method to traverse all sub-directories and copy one file at a time this way (still using the same File::Copy module) ;-)

    UPDATE: actually here is a post to comp.lang.perl.misc that seems to do what you are asking (even without the use of File::Find methods). However, I still believe that doing it the File::Find way is a bit cleaner than with a recurisve method invocation. {grin}

    _____________________
    $"=q;grep;;$,=q"grep";for(`find . -name ".saves*~"`){s;$/;;;/(.*-(\d+) +-.*)$/; $_=["ps -e -o pid | "," $2 | "," -v "," "];`@$_`?{print"+ $1"}:{print" +- $1"}&&`rm $1`; print$\;}
Re: moving directories recursively
by Abigail-II (Bishop) on Jun 03, 2002 at 15:24 UTC
    I'm a bit confused. If the backup directory exists, you delete it, and then you try to move stuff into it. But you never recreated it.

    But since all you want to do is moving everything, not copying, things are very simple. First delete the backup dir if it exists, then do:

    rename $workspace => $backup_dir or die $!;
    That will "recursively" move everything.

    Abigail

      Except it doesn't work across filesystem boundaries.

      Makeshifts last the longest.