Column Sort (Perl)

How can I sort by multiple columns for the code below?

Currently, the code:
1. Receives @listfiles in $directory
2. Uses a regular expression to receive $fileName, $fileLocationand $fileSizefor each element in @list
3. Prints 3 values ​​in (2) to 3 fixed-width columns 4. Then prints the total number of files and directory size

I would like the output to be displayed sorted by:
1. $fileNamethen
2. $fileLocationthen
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
source share
1 answer

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;
+12

All Articles