This is commonly called natural. There is a module that implements it: Sort :: Naturally
To get the maximum value, you can sort and get the last element:
use strict; use warnings; use Sort::Naturally; my @names = (...); my $name_with_biggest_number = (nsort(@names))[-1];
Refresh - Manual Sort
Using map / sort / map idiom . But it will work only if there is one number in the file name:
use strict; use warnings; my @names = (...); my @sorted_names = map { $_->[0] } sort { $b->[1] <=> $a->[1] }
Update - no sorting
Depending on the input, it may be more efficient to avoid using sort . Thus, you can explicitly program the search for the maximum number:
sub name_with_largest_number { my (@names) = @_; my $max_number = undef; my $name_with_max_number = undef; for my $name (@names) { my ($number) = ($name =~ m/(\d+)/); if (defined $number) { if (! defined $max_number || $number > $max_number) { $max_number = $number; $name_with_max_number = $name; } } } return $name_with_max_number; } print name_with_largest_number(...);
source share