Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: Copy dir with space

by duelafn (Parson)
on Jul 10, 2014 at 12:04 UTC ( [id://1093042]=note: print w/replies, xml ) Need Help??


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

    Thanks very much, it did the work :-) Adrian

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1093042]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (5)
As of 2026-04-13 11:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.