Reputation: 55
How to sort array with String looks like this 'name.extension' and sort only with name order.
My program work wrong then file names are 0.ext, 1.ext, ... and files are read in wrong sequence.
My Program looks like this:
#!/usr/bin/perl
use strict;
use warnings;
use File::Basename;
my $args_count = $#ARGV + 1;
if ($args_count != 1) {
print "Usage: perl.pl dir_path\n";
exit;
}
my $dir = $ARGV[0];
chdir $dir
or die "Error - Please check that $dir exists and is accessible.\n";
opendir (DIR, $dir);
my @fileList = readdir DIR;
sort @fileList;
my $count = 0;
print "Old name: | New name:\n";
foreach (@fileList) {
next if -d;
my ($name,$path,$suffix) = fileparse("$_",qr"\.[^.]*$");
my ($ext) = $_ =~ /(\.[^.]+)$/;
rename $name.$ext, $count.$ext;
print "$name$ext >> $count$ext\n";
$count += 1;
}
Upvotes: 0
Views: 232
Reputation: 126722
It probably doesn't matter that the sort
is taking the extension into account, although by default sort
uses a lexical sort so that 11.a
will be sorted before 2.a
. If you want a numeric sort then you need to say so and show the format of your file names.
What is a problem is that you sort the @fileList
array and then throw away the sorted list.
If you want the array sorted, you must write
@fileList = sort @fileList
or if you just want to print them in order, you can sort in the loop, like this
foreach (sort @fileList) { ... }
By the way, please don't use capital letters in local identifier names. They are reserved for global identifiers like Package::Names
. Your array would be much better named @file_list
Upvotes: 4