Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Perl - Copy files to a newly created folder

by fishmonger (Chaplain)
on Apr 18, 2015 at 19:31 UTC ( [id://1123900]=note: print w/replies, xml ) Need Help??


in reply to Perl - Copy files to a newly created folder

This is the way I'd do it, which only uses core modules.

#!/usr/bin/perl use warnings; use strict; use File::Copy; use File::Path qw(make_path); use File::Spec::Functions; use File::Basename; my $dir = 'C:/dev'; my @files = grep { ! -d } <$dir/*>; FILE: foreach my $file (@files) { my ($name, $path, $suffix) = fileparse($file, qr/\.[^.]*/); $suffix or do { warn "$name does not have an ext\n"; next FILE; }; $suffix =~ s/\.//; # (optional) strip leading . my $subdir = catdir($path, $suffix); make_path($subdir) unless -d $subdir; move($file, $subdir) or warn "Failed to move $file to $subdir <$!> +\n"; }

EDIT: If you have spaces in the source path, you will probably need to use quotes when building @files.

Change grep { ! -d } <$dir/*> to grep { ! -d } <"$dir/*">

Replies are listed 'Best First'.
Re^2: Perl - Copy files to a newly created folder
by Benichouniev (Novice) on Apr 19, 2015 at 09:15 UTC

    Fishmonger,
    thanks for your answer! Your code works perfectly (I changed the move to copy to be able to test it several times without having to copy the files again). I also used the quotes around $dir/* for the @files building.
    Now the thing is, I think I understand how your code works, but could you please explain each line so I know exactly how it runs, step by step?
    You have been a great help but now I want to know how it works to be able to do it again in the future, if necessary...
    Could you add #commentaries like this on each line to guide my through?
    That would be extremely helpful! Thanks!
    Ben

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (5)
As of 2024-04-19 21:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found