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";
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With