使用Perl按升序或降序排序单列

时间:2013-09-28 16:26:37

标签: perl

我正在尝试使用Perl对文本文件中的以下价格列进行排序。

Time    Num    Size     Price Act | Act Price   Size    Num       Time  
11:30:12.957    1   3000 11.90  A  |  A  11.05   500     1      11:30:12.954   
11:30:12.957    1   100  11.75  A  |  A  14.00   1676    3      11:30:12.957

我可以将文本文件读入数组并按行排序,但我想不出如何对升序降序顺序中的特定列进行排序? 尝试在文本文件中一次读取一个元素,如下所示,然后尝试按降序排序第一个Price

use strict;
use warnings;

open(my $file_handle, '<', 'Data.txt') or die("Error: File cannot be opend:  $!");

my @words;

while (<$file_handle>) {
chomp;
@words = split(' ');
}

1 个答案:

答案 0 :(得分:2)

use strict;
use warnings;

open(my $file_handle, '<', 'Data.txt') or die("Error: File cannot be opend:  $!");

my @rows;

while (<$file_handle>) {
  $. > 1 or next; # skip header line
  chomp;
  push @rows, [ split ]; # split current line on \s+ 
}

# sort descending on 4-th column
@rows = sort { $b->[3] <=> $a->[3] } @rows;

# ascending sort on same column
# @rows = sort { $a->[3] <=> $b->[3] } @rows;