複数の列を並べ替える(Perl)

どのように私は下のコードの複数の列を介して並べ替えに行くだろうか?

Currently, the code:
1. Gets a @list of files in a $directory
2. Uses regex to get the $fileName, $fileLocation and $fileSize for each element in @list
3. Prints out the 3 values in (2) into 3 fixed-width columns 4. Then prints out the total number of files and directory size

I would like the output to display sorted by:
1. $fileName then
2. $fileLocation then
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";
5

1 答え

独自のソートアルゴリズムを指定し、 ソート することができます。


サンプル実装

結果をハッシュリファレンスで @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;
12
追加された