Sorting file names with Perl
I had to sort directories of pdf files that had identical names except for the last characters before the extension.pdf. Perl has a nice built in sort routine, but when I used it to sort like this:
@sortedlist = sort @listOfFiles;
I would end up with filenames in sort order for the most part except 10 would come after 1 and 20 would come after 2 and so forth. So I wrote a mysort subrouting where I could give it sort criteria. This is what I came up with to make it work:
sub mysort {
@s = sort mycriteria @_;
sub mycriteria {
my($aa) = $a =~ /(\d+\.pdf$)/;
my($bb) = $b =~ /(\d+.pdf$)/;
$aa < => $bb;
}
};
This is a nice way to sort based upon your own criteria. You can change the criteria by editing the regular expressions. $a and $b are automatic scalars in the sort routine, so you have to pass the edited values into new scalars ($aa, $bb) and do your sort upon those.
I then called the sort with an array like this: my @newlist = mysort(@movelist);