Ronen Kfir wrote:
> 
> I need to delete oldest modified file in a directory. I find this file with this:
> 
> my $oldest= printf "%s\n", (sort{ (-M $b) <=> (-M$a) } glob("v:\*"));
> print $oldest;
> 
> unlink "$oldest";
> 
> What I get in response is:
> 
> oldest_filename
> 1
> 
> File is not deleted.
> 
> How would I do it?

As you have observed, printf returns true if it worked (or false if it
didn't.)  You
could do it like this:

my ( $oldest ) = sort { (-M $b) <=> (-M $a) } glob "v:\*";

unlink $oldest or warn "Cannot delete $oldest: $!";


Or like this:

my $oldest = ( sort { (-M $b) <=> (-M $a) } glob "v:\*" )[ 0 ];

unlink $oldest or warn "Cannot delete $oldest: $!";


But both of those methods use an inefficient sort because you are
stat()ing each
file more than once.  Here are two methods that only stat()s each file
once.

my ( $oldest ) = map $_->[ 0 ],
                 sort { $b->[ 1 ] <=> $a->[ 1 ] }
                 map [ $_, -M ],
                 glob "v:\*";

unlink $oldest or warn "Cannot delete $oldest: $!";


This is the most efficient as it only stat()s each file once and it
doesn't have to sort.

my $oldest = [ '', 0 ];
for my $file ( glob "v:\*" ) {
    my $date = -M $file;
    $oldest = [ $file, $date ] if $oldest->[ 1 ] < $date;
    }

unlink $oldest->[ 0 ] or warn "Cannot delete $oldest->[0]: $!";



John
-- 
use Perl;
program
fulfillment

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to