2012-09-25 77 views
1

我對Perl比較陌生。我有一個名爲$ TransRef的數組的引用,其中包含對數組的引用。我的目標是編寫一個將$ TransRef參數作爲唯一參數的sub,通過第二個元素(一個字符串)對基礎數組的引用進行排序,並將輸出設置回$ TransRef引用。有人可以展示如何在Perl中完成這項工作嗎?Perl對數組引用進行排序

下面是一些生成$ TransRef的代碼。它尚未測試,並可能有一些錯誤:

# Parse the data and move it into the Transactions container. 
for ($Loop = 0; $Loop < 5; $Loop++) 
{ 
    $Line = $LinesInFile[$Loop]; 
    # Create an array called Fields to hold each field in $Line. 
    @Fields = split /$Delimitor/, $Line; 
    $TransID = $Fields[2]; 
    # Save a ref to the fields array in the transaction list. 
    $FieldsRef = \@Fields; 
    ValidateData($FieldsRef); 
    $$TransRef[$Loop] = $FieldsRef; 
} 
SortByCustID($TransRef); 

sub SortByCustID() 
{ 
    # This sub sorts the arrays in $TransRef by the 2nd element, which is the cust #. 
    # How to do this? 
    my $TransRef = @_; 
    ... 
} 
+0

一些代碼如何?你還嘗試過什麼? –

+1

顯示您正在討論的數據結構。 – TLP

+1

TLP:描述看起來相當完整且毫不含糊。不尋常的,我知道:) – ysth

回答

5

很簡單:

sub sort_trans_ref { 
    my $transRef = shift; 
    @$transRef = sort { $a->[1] cmp $b->[1] } @$transRef; 
    return $transRef; 
} 

雖然這將是更自然的我不修改原始數組:

sub sort_trans_ref { 
    my $transRef = shift; 
    my @new_transRef = sort { $a->[1] cmp $b->[1] } @$transRef; 
    return \@new_transRef; 
} 
+0

謝謝。這看起來應該起作用。自從你第一次回答以來,我選擇你的答案作爲解決方案。 –

+1

另外,我想你提出的將引用返回給新排序數據的建議可能是更好的方法,因爲它使代碼更加模塊化。 –

1
sub string_sort_arrayref_by_second_element { 

    my $param = shift; 
    @$param = sort { $a->[1] cmp $b->[1] } @$param; 

}