in reply to Directory Listing

I'd suggest two small changes. First, don't stat just your $_ variable - since you are doing an opendir, only the names of the files are returned, not the full path. In this particular case, it is okay, but something to get in the habit of so it does not nail you later. Second, you can simply swap the order of the sort arguments instead of using a reverse. Not a big deal, but a little more compact and readable (IMO). I kept the nice map idea from agoth and also added another argument, in case you feel like sorting by somthing else.

my $dir = shift || "."; my $field = shift || 10; opendir(DIRH, $dir) or die "Cannot open $dir: $!"; my %file = map { $_ => (stat("$dir/$_"))[$field]} grep { !/^\.\.?$/ && /pm$/ } readdir DIRH; closedir(DIRH); for (sort { $file{$b} cmp $file{$a} } keys %file) { print "$_ , $file{$_} \n"; }

Replies are listed 'Best First'.
Re: Re: Directory Listing
by repson (Chaplain) on Jan 09, 2001 at 18:29 UTC
    If your trying to cut it down then you don't really need the hash, since an array dereference is maybe/probably faster than a hash lookup.
    my $dir = shift || "."; my $field = shift || 10; opendir(DIRH, $dir) or die "Cannot open $dir: $!"; for ( sort { $b->[1], $a->[1] } map { [ $_, (stat("$dir/$_"))[$field] ] } grep { !/^\.\.?$/ && /pm$/ } readdir(DIRH) ) { print join("\t", @$_) . "\n"; } closedir(DIRH);

    Update: fixed a few errors, which turnstep pointed out.