On Friday 30 November 2007 11:04, icarus wrote:
> Thanks Rob and Martin for your inputs.
>
> I found a solution to my problem.

Well, at least part of the solution.

> I'm posting it here for whoever might need it.

I would advise that no one else *needs* this solution.  :(

> I'm sure there's a faster solution out there but this
> will do just fine.
> I had to put the files in an array. :(
> The reason is that you cannot sort a scalar [ or scalar context such
> as reading a dir using while (<MYDIR>) ] , it has to be an array.
>
>
> use strict;
> use warnings;
>
> my $path = "/home/icarus/files";
> my $time_var = "-M";
>
> opendir (MYDIR, $path) or die $!;
>
> #from older to newest.  If you want from newest to oldest, switch the
> $b for $a then <=> $a for $b
> my @files = sort { eval($time_var.' "$path/$b" <=> '.$time_var.'
> "$path/$a"') } grep { -f "$path/$_" } readdir(MYDIR);
> my @sorted = @files;

*DO* *NOT* *USE* eval() *TO* *DO* *THIS*.  Do this instead:

sub newest { -M "$path/$a" <=> -M "$path/$b" };
sub oldest { -M "$path/$b" <=> -M "$path/$a" };

#from older to newest.  If you want from newest to oldest, switch to 
'oldest'
my @sorted = sort newest grep -f "$path/$_", readdir MYDIR;


But it would be more efficient to use a Schwartzian Transform.

perldoc -f sort


> closedir(MYDIR);
>
>
> foreach (@sorted){
>    sleep 5; #just to have time to compare
>    print "$_\n";
> }


John
-- 
use Perl;
program
fulfillment

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to