How to compare file names in perl

I have a list of file names in the form integer_Name.txt . I want to return the file name with the highest integer value. Can this be done in perl other than string comparisons?

+1
source share
2 answers

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] } ## descending order map { [ $_, m/(\d+)/ ] } ## extracting first number @names; my $name_with_biggest_number = $sorted_names[0]; 

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(...); 
+5
source

Edit: Here is an alternative that does not need expensive sorting. Thanks @tchrist for pointing out how stupid the view is.

 use strict; use warnings; use Data::Dumper; my @list = qw( 332_Name.txt 999_Name.txt 125_Name.txt 9_Name.txt 0066_Name.txt ); my %mapping; my $highest = 0; foreach(map { m/(\d+)/; $mapping{$1} = $_; $1 } @list) { $highest = $_ if $_ > $highest; } print $mapping{$highest}; 
+1
source

Source: https://habr.com/ru/post/1200042/


All Articles