2011-12-19 122 views
5

我將如何進行下列代碼的多列排序?對多列進行排序(Perl)

目前,代碼:
1.獲取文件的@list$directory
2.使用正則表達式來獲取每個元素的$fileName$fileLocation$fileSize@list
3.打印出3個值(2)轉換成3個固定寬度的列 4.然後打印出的文件的總數和目錄大小

我想輸出到顯示排序方法:
1. $fileName然後
2. $fileLocation然後

$directory = '/shared/tmp'; 
$count = 0; 

@list = qx{du -ahc $directory}; 

printf ("%-60s %-140s %-5s\n", "Filename", "Location", "Size"); 

foreach(@list) { 
    chop($_);              # remove newline at end 
    if (/^(.+?K)\s+(.+\/)(.+\.[A-Za-z0-9]{2,4})$/) {    # store lines with valid filename into new array 
# push(@files,$1); 
    $fileSize = $1; 
    $fileLocation = $2; 
    $fileName = $3; 
    if ($fileName =~ /^\./) { 
     next; } 
    printf ("%-60s %-140s %-5s\n", $fileName, $fileLocation, $fileSize); 
    $count++; 
    } 
    else { 
    next; 
    } 
} 

print "Total number of files: $count\n"; 

$total = "$list[$#list]"; 
$total =~ s/^(.+?)\s.+/$1/; 
print "Total directory size: $total\n"; 

回答

11

您可以指定自己的排序算法,並給它sort


示例實現

把你的結果(散列引用)到名爲@entries一個數組,並使用類似下面的。

my @entries; 

... 

# inside your loop 

    push @entries, { 
    'filename' => $fileName, 
    'location' => $fileLocation, 
    'size'  => $fileSize 
    }; 

... 

my @sorted_entries = sort { 
    $a->{'filename'} cmp $b->{'filename'} || # use 'cmp' for strings 
    $a->{'location'} cmp $b->{'location'} || 
    $a->{'size'}  <=> $b->{'size'}  # use '<=>' for numbers 
} @entries;