我正在用 Perl 编写一个脚本,我想在给定目录中的所有 .csv
文件上运行。文件名的类型为:CCCC0.csv, CCCC1.csv, ..., CCCC198.csv
。但是,我希望 Perl 首先在文件 CCCC0.csv
上运行脚本,而不是在 CCCC1.csv
等上运行...所以,基本上,根据增加的值文件名末尾的数字。
如果我写:
#!/usr/bin/perl
use strict;
use warnings;
use diagnostics;
my $file;
my @files = <*.csv>;
my @orderedfiles = sort @files;
for $file (@orderedfiles) {
... do stuff
}
它首先运行在 CCCC100.csv
而不是 CCCC11.csv
而如果我写
#!/usr/bin/perl
use strict;
use warnings;
use diagnostics;
my $file;
my @files = <*.csv>;
my @orderedfiles = sort { substr($a, 4) <=> substr($b, 4) } @files;
for $file (@orderedfiles) {
... do stuff
}
它给了我一个错误,告诉我我没有订购数字(我假设他不明白这是 4 个字符之后的数字而不是另一个字符。) 我已经查看了关于 Stackoverflow 或 perlmonks 的无数问题,但我一直无法找到我的问题的答案。
编辑:我使用的是 Windows 机器。
最佳答案
您几乎就在那里……“.CSV”仍然在那里。最好使用正则表达式来读取数字字符。
my @sorted = sort { ($a =~ /(\d+)/)[0] <=> ($b =~ /(\d+)/)[0] } @files;
有一个成语叫Schwartzian Transform也可以做到这一点,虽然需要 CS 专业才能理解 :D
my @sorted = map { $_->[0] } # return the sorted file names
#
sort { $a->[1] <=> $b->[1] } # sort on the numeric portion
#
map { [$_, /(\d+)/] } # wrap the file names in a temporary
@files; # array with their numeric portions.
# ^^ read from bottom to top ^^
关于perl - 在 Perl 中对文件名进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28229008/