2013-09-28 149 views
1

我正尝试使用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(' '); 
} 
+0

你的意思是“列排序”排序,或“排序行*由*列“? – AmbroseChapel

+0

我试图对列进行排序 – user2795662

回答

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; 
+0

感谢这对我有用 – user2795662

+0

如果我尝试使用for循环打印出@rows的内容,如下所示:for(my $ i = 0; $ i <= $#rows; $ i ++){ \t print $ rows [$ i]。 “\ n” 个; \t} - 我得到的内存位置ARRAY(0x966bac) - 你知道我怎么能得到实际值? – user2795662

+0

感谢您的帮助 – user2795662

相关问题