Sort across multiple columns (Perl)

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

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

Answers


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


A sample implementation

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;

Need Your Help

How to make overflow-x: hidden on android browser?

android overflow android-browser

I understand from several sources that android browser does not recognize overflow property. Please help me find a work-around for that. Thank you!

CSS3 3d transforms - Overlapping divs with different z-indexes has different results for webkit browsers

css css3 webkit 3d

I am trying to figure out which browser is not implementing this right: I have 2 divs positioned on top of each other. For the front one I rotate the Y axis and translate the X axis. Now for this s...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.