跨多列排序(Perl)

kur*_*uki 5 sorting perl

我将如何针对以下代码对多列进行排序?

目前,代码:
1.获取a中的一个@list文件$directory
.使用正则表达式获取$fileName,$fileLocation$fileSize使用3中的每个元素@list
.将(2)中的3个值打印成3个固定宽度列4.然后打印出总数文件数和目录大小

我希望输出显示排序依据:
1.$fileName然后
2. $fileLocation然后
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";
Run Code Online (Sandbox Code Playgroud)

Fil*_*efp 15

您可以指定自己的排序算法并将其赋予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;
Run Code Online (Sandbox Code Playgroud)