跨多列排序(Perl) [英] Sort across multiple columns (Perl)

查看:180
本文介绍了跨多列排序(Perl)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于下面的代码,我将如何对多列进行排序?

How would I go about sorting across multiple columns for the below code?

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

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

我希望显示的输出按以下顺序排序:
1. $fileName然后
2. $fileLocation然后
3. $fileSize

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

推荐答案

您可以指定自己的排序算法,并将其提供给 sort

You can specify your own sorting algorithm and give it to sort!

示例实现

将结果(在哈希引用中)推入名为@entries的数组,并使用类似下面的内容.

Push your results (in a hash reference) into an array called @entries, and use something like the below.

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;

这篇关于跨多列排序(Perl)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆