This is my first ever real 100% self made perl script, I'd like to know how I can improve it.
#!/usr/bin/env perl
#this script takes a directory and sorts the files into folders by file ending
use strict;
use warnings;
use File::Copy;
sub sort_files {
my $dir = shift || '.'; #cwd if no directory given
$dir =~ s/\/$//; #remove trailing /
opendir(DIR, $dir) or die $!;
my @files = grep {
!/^\./ #does not start with .
&& -f "$dir/$_" #is file
} readdir DIR;
my $len = @files;
print "sorting $len files\n";
foreach my $file (@files){
my ($ext) = $file =~ /([^.]*$)/;#grabs file extension
my $dest = "$dir/$ext/";
if (not -d "dest"){ #create folder if it does not exist
mkdir $dest;
print "\tcreated directory $dest\n";
}
move "$dir/$file", $dest or die "$!";
print "\t$file moved to $dest\n"
}
}
sort_files @ARGV;
exit 0;
ninja edit: I just noticed that this script runs into problems if there is no file ending specified. Elegant solutions apreciated! (checking the file for !/\./
would work, but that's not elegant in my book)