Ed wrote:
> I'm having a difficult time finding a way to traverse a directory structure
> and then perform some simple operations on files in the directories.
> 
> I want to traverse a directory structure and then remove the oldest file in
> each subdirectory. Something like this:
> 
> ## traverse the directories and in each directory, if there are at least N
> files in the directory, in remove the oldest file in that directory.
> ##
> foreach($dir (@dirs) )
> {
>   ## if $dir has > N files of "*.ext"
>   ## unlink the oldest one.
> }
> 
> I've been Looking at File::Find but I'm baffled by the examples and usage
> and the "wanted" function.
> 
> Where can I look to find some modules and functions for this?

This may help get you started:

#!/usr/bin/perl
use warnings;
use strict;
use File::Find;

# Get the directory from the command line
# or use the current directory
my $search = shift || '.';

# Get an array of all subdirectories
my @dirs;
find sub { push @dirs, $File::Find::name if -d }, $search;

for my $dir ( @dirs ) {
    opendir my $dh, $dir or do {
        warn "Cannot open '$dir' $!";
        next;
        };
    my ( $name, $time ) = ( '', ~0 );
    while ( my $file = readdir $dh ) {
        my $mtime = ( stat "$dir/$file" )[ 9 ] or do {
            warn "Cannot stat '$dir/$file' $!";
            last;
            };
        ( $name, $time ) = ( $file, $mtime ) if -f _ and $time > $mtime;
        }
    unlink "$dir/$name" or warn "Cannot unlink '$dir/$name' $!";
    }

__END__




John
-- 
use Perl;
program
fulfillment

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


Reply via email to