2011-12-19 15 views
5

Jak mam posortować wiele kolumn dla poniższego kodu?Sortowanie między wieloma kolumnami (Perl)

Obecnie kod:
1. Pobiera @list plików w $directory
2. Używa regex, aby uzyskać $fileName, $fileLocation i $fileSize dla każdego elementu w @list
3. wypisuje wartości 3 w (2) na 3 kolumny o stałej szerokości 4. Następnie wypisuje całkowitą liczbę plików i rozmiar katalogów

Chciałbym wyświetlającego posortowane wg:
1. $fileName następnie
2. $fileLocation następnie
3. $fileSize

$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"; 

Odpowiedz

11

Można określić własny algorytm sortowania i dać go do sort!


Próbkę realizacja

Push wyniki (w odniesieniem hash) do tablicy o nazwie @entries i użyć coś jak poniżej .

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; 
Powiązane problemy