in reply to Copy dir with space
Generally files with spaces are no problem as long as you are not using the shell. You didn't include your code for the copy function, but if it works on directories without spaces, I expect it uses the cp shell command (which can be dangerous depending on how it is used and exactly how it is implemented).
The code below will be safe as it never passes the file names to the shell.
#!/usr/bin/perl use strict; use warnings; use Path::Class; use File::Copy::Recursive qw/ dircopy /; my $source = "/pr/perl_by_example"; my $dest = "/pr/book"; for my $path (dir($source)->children) { next if $path =~ /\./; my $target = dir($dest, $path->basename); dircopy $path, $target or die "Error copying $path: $!"; }
dir($source)->children will not include the '.' and '..' special directories, but will include everything else (including hidden files and directories). Thus, I left your $path =~ /\./ test in place. However, that test looks suspicious since it will match a '.' anywhere in the name (beginning, middle, end) so will usually match file names as well (but not always, since not all file names have an extension). To exclude hidden files and directories use: next if $path =~ /^\./; To exclude all files and only copy directories next unless $path->is_dir; If you want to exclude both (all hidden files and directories as well as all file), I would suggest including both tests separately:
for my $path (dir($source)->children) { next if $path =~ /^\./; # exclude hidden files and directories next unless $path->is_dir; # exclude files my $target = dir($dest, $path->basename); dircopy $path, $target or die "Error copying $path: $!"; }
Good Day,
Dean
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Copy dir with space
by adriang (Sexton) on Jul 10, 2014 at 15:00 UTC |