my %h; foreach $file (sort { ($h{$a} ||= (stat $a)[9]) <=> ($h{$b} ||= (stat $b)[9]) } @allfiles) { ...;