我需要在perl中按升序排列数组值,我使用排序比较选项获取以下值但不能正常工作,请尽快帮助
p1.txt
p10.txt
p11.txt
p12.txt
p13.txt
p14.txt
p15.txt
p16.txt
p17.txt
p18.txt
p19.txt
p2.txt
p20.txt
p21.txt
p22.txt
p23.txt
p24.txt
p3.txt
p4.txt
p5.txt
p6.txt
p7.txt
p8.txt
p9.txt
注意:我想排序数组值而不是数组索引
提前致谢
答案 0 :(得分:3)
如何使用schwartzian变换,doc here和here:
my @unsorted = qw(
p1.txt
p10.txt
p11.txt
p12.txt
p13.txt
p14.txt
p15.txt
p16.txt
p17.txt
p18.txt
p19.txt
p2.txt
p20.txt
p21.txt
p22.txt
p23.txt
p24.txt
p3.txt
p4.txt
p5.txt
p6.txt
p7.txt
p8.txt
p9.txt
);
my @sorted = map { $_->[0] }
sort { $a->[1] <=> $b->[1] }
map { (my $t=$_)=~s/\D+//g; [$_, $t] }
@unsorted;
dump@sorted;
<强>输出:强>
(
"p1.txt",
"p2.txt",
"p3.txt",
"p4.txt",
"p5.txt",
"p6.txt",
"p7.txt",
"p8.txt",
"p9.txt",
"p10.txt",
"p11.txt",
"p12.txt",
"p13.txt",
"p14.txt",
"p15.txt",
"p16.txt",
"p17.txt",
"p18.txt",
"p19.txt",
"p20.txt",
"p21.txt",
"p22.txt",
"p23.txt",
"p24.txt",
)
答案 1 :(得分:1)
考虑使用Sort::Naturally执行此任务:
use strict;
use warnings;
use Sort::Naturally qw/nsort/;
chomp( my @data = <DATA> );
print "$_\n" for nsort @data;
__DATA__
p1.txt
p10.txt
p11.txt
p12.txt
p13.txt
p14.txt
p15.txt
p16.txt
p17.txt
p18.txt
p19.txt
p2.txt
p20.txt
p21.txt
p22.txt
p23.txt
p24.txt
p3.txt
p4.txt
p5.txt
p6.txt
p7.txt
p8.txt
p9.txt
部分输出:
p1.txt
p2.txt
p3.txt
p4.txt
p5.txt
p6.txt
p7.txt
p8.txt
p9.txt
p10.txt
p11.txt
p12.txt
...
p22.txt
p23.txt
p24.txt
希望这有帮助!
答案 2 :(得分:0)
您需要创建自己的排序算法并将其传递给sort:
sub custom_sort
{
$a =~ /^p(\d+)\.txt$/; #capture the number in $a
my $intA = $1;
$b =~ /^p(\d+)\.txt$/; #capture the number in $b
my $intB = $1;
return ($intA <=> $intB); #compare the numbers and return
}
并致电:
@sortedArray = sort custom_sort @array;
请参阅:http://perldoc.perl.org/functions/sort.html和http://perldoc.perl.org/perlop.html#Equality-Operators
答案 3 :(得分:0)
最简单的方法是使用nsort_by
中的List::UtilsBy
功能;这会按照代码块返回的数字对列表进行排序。然后,您将使用代码块调用此方法以从文件名中提取数字:
use List::UtilsBy qw( nsort_by );
my @sorted = nsort_by { /^p(\d+)\.txt$/ and $1 } @array;