drodinthe559 has asked for the wisdom of the Perl Monks concerning the following question:

Hello All - I'm trying to do a column sort on an array of an array based on the modification date. This is real frustrating getting this s to work. Basically I want sort on the date field so I can rename each file based on that. Any help will be greatly appreciated.
use strict; use File::Find; use File::stat; my @results; find(\&search, "c:/test"); sub search { if ($_ =~ m/ACH/ ) { push @ {$results[0]}, $_; push @ {$results[1]}, stat($_)->mtime; } } my @temp = reverse sort { $a->[0] cmp $a->[0]} @results; foreach my $x (@temp){ #print $results . "\n"; print $x->[0] . "\t" . $x->[1] . "\n"; }

Replies are listed 'Best First'.
Re: Column Sort on Array
by BrowserUk (Patriarch) on Jul 19, 2008 at 13:11 UTC

    Picking out the sort from the tangle of unformatted code I see:

    my @temp = reverse sort { $a->[0] cmp $a->[0]} @results;

    If you compare $a->[0] against $a->[0], it will always be equal, so sort will do nothing. Is that the problem you are experiencing?

    Try replacing one of the $a with $b and see what difference it makes.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      I tried that with no luck. When I run it in Komodo, I notice that variable don't change no matter what I change in that line. I tried this. my @temp = reverse sort { $a->[0] cmp $b->[0]} @results;
Re: Column Sort on Array
by cdarke (Prior) on Jul 19, 2008 at 13:15 UTC
    1. Try using code tags:
    use strict; use warnings; use File::Find; use File::stat; my @results; find(\&search, "c:/test"); sub search { if ($_ =~ m/ACH/ ) { push @ {$results[0]}, $_; push @ {$results[1]}, stat($_)->mtime; } } my @temp = reverse sort { $a->[0] cmp $a->[0]} @results; foreach my $x (@temp){ #print $results . "\n"; print $x->[0] . "\t" . $x->1 . "\n"; }
    In the sort you are comparing $a->[0] with $a->[0], should probably be:
    my @temp = reverse sort { $a->[0] cmp $b->[0]} @results;
    However I'm puzzled. You seem to be putting the mtime field into element 1, yet you are comparing element zero. Also, if you want to compare numbers then you should use <=> rather than cmp.
    A reply falls below the community's threshold of quality. You may see it by logging in.