in reply to Sorting Files with Numbers

Try this. (untested)

foreach my $file (sort {substr($a,4) <=> substr($b,4)} keys %hash) { print "$key \n"; }
This compares everything except the first 4 characters using the numeric comparision operator. <=>.

Examine what is said, not who speaks.

Replies are listed 'Best First'.
Re: Re: Sorting Files with Numbers
by hardburn (Abbot) on Dec 30, 2002 at 17:07 UTC

    I'm guessing that 'file' was just an example of a name that the orginal poster was using. It isn't very likely that the filenames will be exactly 4 chars long followed by a number. This will probably work better (untested):

    sub file_sort { $a =~ /(\d*)$/; my $a_num = $1; $b =~ /(\d*)$/; my $b_num = $1; $a_num <=> $b_num; } foreach my $file (sort &file_sort keys %hash) { print "$key \n"; }

      Your solution fails to sort by the alpha prefix first. See dragonchild's answer, above, which groups files first by their alpha prefix, then numerically by suffix.

      Update: jdporter's solution (here) might be even more efficient with this dataset, since it uses \D+ (non-digits) rather than \w+ (word characters) to match the prefix, but it will also match punctuation and other non-alpha characters (which may not be what you want).