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

The piece of code below looks into a folder called test in f: and and checks all directories for a certain ae and moves to oldbackups in F: , but the script fails with the error below. Issue is it tries to overwrite oldbackups but it should be creating files inside oldbackups. i need to append the sudirectory names within f:\test loaded in @dirs and append it to f:\oldbackups within the for loop. how do we achieve that?
use warnings; use File::Copy; use File::Spec::Functions qw( catfile ); use File::Find; my $dir = 'F:\\test'; my $newlocation = 'F:\\oldbackups'; opendir(my $dh, $dir) or die("Can't open directory \"$dir\": $!\n"); my @dirs; while (defined(my $fn = readdir($dh))) { next if $fn eq '.' || $fn eq +'..'; my $qfn = catfile($dir, $fn); if (-d $qfn && -M $qfn > 0) { push @dirs, $qfn; # or $fn } } foreach ( +@dirs) { print("Directory to be moved : $_\n"); } foreach my $dr (@dirs){ move("$dr", "$newlocation") || die "$!"; print "Moved $dr to $newlocation\n"; } output: D:\Software\scripts>cqperl test2.pl Directory to be moved : F:\test\New Folder (2) Directory to be moved : F:\test\New Folder (3) Directory to be moved : F:\test\New Folder (4) Directory to be moved : F:\test\test2 Permission denied at test2.pl li +ne 26.
  • Comment on How to append a sub directory name alone to an existing dir path ?
  • Download Code

Replies are listed 'Best First'.
Re: How to append a sub directory name alone to an existing dir path ?
by ikegami (Patriarch) on Nov 13, 2007 at 21:50 UTC

    catfile, like you are already doing for the source directory.

    use strict; use warnings; use File::Copy qw( move ); use File::Spec::Functions qw( catfile ); my $src_dir = 'F:\\test'; my $dst_dir = 'F:\\oldbackups'; opendir(my $dh, $src_dir) or die("Can't open directory \"$src_dir\": $!\n"); my @dirs; while (defined(my $fn = readdir($dh))) { next if $fn eq '.' || $fn eq '..'; my $src_qfn = catfile($src_dir, $fn); next if !(-d $src_qfn && -M $src_qfn > 0); my $dst_qfn = catfile($dst_dir, $fn); move($src_qfn, $dst_qfn) or die("Can't move directory \"$src_qfn\" to \"$dst_qfn\": $!\n" +); }