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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.