Perl Newby has asked for the wisdom of the Perl Monks concerning the following question:

I have a directory that contains a number of text files. The text files follow a naming convention, as follows:
mlb_boxscore$200 mlb_boxscore$221 mlb_boxscore$824 mlb_boxscore$386 mlb_boxscore$149
I want to be able to sort these files and only pull out the 1 file that has the largest number after the $. After this file is pulled out of the C drive, for example, I want it placed in another directory, such as the D drive. Any suggestions would be appreciated.

Replies are listed 'Best First'.
Re: Sorting on Files
by tadman (Prior) on May 16, 2001 at 00:23 UTC
    Assuming the files are numbered with a fixed width, such as three digits that you have here in your example, you can sort the output of readdir and pick off the first entry. If you're not familiar with this method, try this:
    my $base_dir = "c:/data/"; my $new_dir = "d:/new/"; opendir (DIR, $base_dir) || die "Could not open data directory\n"; my ($top_file) = reverse sort readdir(DIR); closedir (DIR);
    Note that this is assigning the first element of the sorted, reversed array from readdir into $top_file. As sort usually goes from lowest to highest (i.e. a .. z), using reverse will give you the highest.

    If your files have a variable number of digits, this sort routine will fail miserably, as the order will be something like 1, 10, 11, 2, 20. You will have to write a "custom" numerical sort routine: my ($top_file) = reverse sort { ($a=~/\$(\d+)$/)<=>($b=~/\$(\d+)$/) } readdir(DIR); Which has the effect of extracting the numerical component from each entry (\d+ is one or more digits). An interesting twist is that you can switch $a and $b and remove reverse because you are now defining the sort rules.

    To move the file from one drive to another is, if I recall correctly, something that might require the use of File::Copy. As in:
    use File::Copy; move($base_dir.$top_file, $new_dir.$top_file);
      sort { $b cmp $a } is more efficient than reverse sort
                      - Ant
Re: Sorting on Files
by stephen (Priest) on May 16, 2001 at 00:31 UTC
    I'll describe the tools you need to get this done, then leave the dirty work to you. :)

    You can sort the filenames using sort(), and you can write your own comparison subroutine. See perlfunc:sort for details.

    You can use substr() to get the number at the end. See perlfunc:substr for details.

    You can use '<=>' to compare the numbers. See perlman:perlop for details.

    stephen