我正在用這樣的檔案詳細資訊值填充一個陣列:
push(@local_files,{fname=>$bname, fdate=>$lfdate, fsize=>$lfsize});
然后嘗試根據 'fname' 降序對它們進行排序,如這些示例和許多其他示例所示:
my @sorted=sort { $b->{'fname'} <=> $a->{'fname'} } \@local_files;
my @sorted=sort { $local_files['fname']{$b} cmp $local_files['fname']{$a} } @local_files;
我沒有嘗試過對這個陣列進行排序,這就是我需要幫助的地方。
但是使用 dumper 我可以看到值存盤在陣列中
foreach my $whatever(@sorted){
## this works to dump contents of whatever
print Dumper(\$whatever);
}
給我這樣的輸出(片段):
{
'fdate' => '88.837662037037',
'fname' => 'Testfile997.txt',
'fsize' => 4415
},
{
'fdate' => '88.837662037037',
'fname' => 'Testfile998.txt',
'fsize' => 4415
},
最終,我希望能夠按存盤的 3 個值中的任何一個進行排序,但多次搜索沒有用。任何幫助表示贊賞 - 謝謝
uj5u.com熱心網友回復:
你幾乎第一次就有了。正確的:
my @sorted = sort { $b->{ fname } cmp $a->{ fname } } @local_files;
您有一個流浪\者,并且您正在執行數字比較而不是字串比較。(我洗掉了不需要的',但這沒關系。)
它也可以用 Sort-Key 很好地完成。
use Sort::Key qw( rskeysort );
my @sorted = rskeysort { $_->{ fname } } @local_files;
請注意,如果您有Testfile99(而不是Testfile099) 和Testfile100(因為9出現在 之后1),那么上述兩種情況都會出現問題。使用自然排序就可以了。
use Sort::Key::Natural qw( rnatkeysort );
my @sorted = rnatkeysort { $_->{ fname } } @local_files;
我希望能夠按存盤的 3 個值中的任何一個進行排序
use Sort::Key::Natural qw( rnatkeysort );
my %sorters = (
by_fname_desc => sub { rnatkeysort { $_->{ fname } } @_ },
...
);
my $order = "by_fname_desc"; # Or whatever
my $sorter = $sorters{ $order }
or die( "Unknown order `$order`" );
my @sorted = $sorter->( @local_files );
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/521575.html
標籤:数组排序perl哈希
