use 5.020; use warnings; use File::Copy; my $in_dir = '/tmp/foo'; my $out_dir = '/tmp/bar'; opendir(my $dir_handle, $in_dir) or die "Can't open directory '$in_dir': '$!'\n"; my @files = readdir($dir_handle); closedir $dir_handle; # Eliminate entries starting with '.' @files = grep { $_ !~ /^\./ } @files; # Split the file names in their numeric and non-numeric part my @unsorted = map { [/^(\d+)(.*)/] } @files; # Sort by numbers first, non-numeric part second my @sorted = sort { $a->[0] <=> $b->[0] or $a->[1] cmp $b->[1] } @unsorted; # ...and re-build the filenames, re-using our old array @files = map { $_->[0] . $_->[1] } @sorted; # Finally, copy the stuff my $file_number = 1; for my $file(@files) { copy("$in_dir/$file", "$out_dir/${file_number}.gif") or die "The copy operation for '$file' failed: '$!'"; $file_number++; }