Search code examples
perlsortingreaddir

Sorting a directory in perl, taking numbers into account


I think I need some sort of Schwartzian Transform to get this working, but I'm having trouble figuring it out, as perl isn't my strongest language.

I have a directory with contents as such:

album1.htm
album2.htm
album3.htm
....
album99.htm
album100.htm

I'm trying to get the album with the highest number from this directory (in this case, album100.htm). Note that timestamps on the files are not a reliable means of determining things, as people are adding old "missing" albums after the fact.

The previous developer simply used the code snippet below, but this clearly breaks down once there are more than 9 albums in a directory.

opendir(DIR, PATH) || print $!;
@files = readdir(DIR);
foreach $file ( sort(@files) ) {
    if ( $file =~ /album/ ) {
        $last_file = $file;
    }
}

Solution

  • If you just need to find the album with the highest number, you don't really need to sort the list, just run through it and keep track of the maximum.

    #!/usr/bin/perl 
    
    use strict;
    use warnings;
    
    my $max = 0;
    
    while ( <DATA> ) {
        my ($album) = $_ =~ m/album(\d+)/;
        $max = $album if $album > $max;
    }
    
    print "album$max.htm";
    
    __DATA__
    album1.htm
    album100.htm
    album2.htm
    album3.htm
    album99.htm