Although you can use opendir and readdir to search through a directory, I think that using File::Find may be a better approach. I have to admit that I personally struggle to understand how to use File::Find directly, so I opt to use File::Find::Rule instead, which provides a different interface to File::Find.
Here's a different approach using File::Find::Rule:
use strict; use warnings; use feature 'say'; use File::Copy; use File::Spec::Functions; use File::Find::Rule; use File::Path qw(make_path); use Cwd; my $pwd = cwd(); my $dir = catdir($pwd,'source'); my $rule = File::Find::Rule->new; $rule->file; $rule->maxdepth(1); my @files = $rule->in($dir); foreach my $file (@files) { my ($extension) = ($file =~ m/.+\.(.+)/); my $subdir = catdir($dir,$extension); if (!(-d $subdir)) {make_path($subdir);} copy($file,$subdir); }
Here's the initial test directory that I used to test the script:
source test1.gif test1.pdf test1.txt test2.gif test2.pdf test2.txt test3.gif test3.pdf test3.txt
Here's the result after running the script:
source test1.gif test1.pdf test1.txt test2.gif test2.pdf test2.txt test3.gif test3.pdf test3.txt gif test1.gif test2.gif test3.gif pdf test1.pdf test2.pdf test3.pdf txt test1.txt test2.txt test3.txt
Although my code above doesn't deal with deleting the original file, I think that you should be able to modify it to meet your needs.
In reply to Re: Perl - Copy files to a newly created folder
by dasgar
in thread Perl - Copy files to a newly created folder
by Benichouniev
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |