2013-09-28 150 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

相關問題