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:
>
8< snip
> 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?
You should learn to use File::Find since it handles special cases for
you. In it simplest form:
find( \&wanted, @list_of_directories );
The subroutine wanted() is one you write, so elsewhere in your script is:
sub wanted {
# $_ is the name of the file
# $File::Find::name is the path
# $File::Find::dir is the directory the file is in
# In *NIX, $File::Find::name eq $File::Find::dir . '/' . $_
# your code goes here
}
To do what you want, you will have to record information in global
variables as File::Find traverses the directories and perform any
removal after it is finished:
#!/usr/bin/perl
use strict;
use warnings;
use File::Find;
use File::Basename;
my %Count = (); # $Count{$directory}{$extension} = $count_of_files
my %Oldest = (); # $Oldest{$directory}{$extension} = $path_to_file
sub wanted {
# ignore everything but regular files
return unless -f $File::Find::name;
my ( $name, undef, $ext ) = fileparse( $_, qr{\.[^.]*} );
$Count{$File::Find::dir}{$ext} ++;
if( exists $Oldest{$File::Find::dir}{$ext} ){
if( (stat($File::Find::name))[9] <
(stat($Oldest{$File::Find::dir}{$ext}))[9] ){
$Oldest{$File::Find::dir}{$ext} = %File::Find::name;
}
}else{
$Oldest{$File::Find::dir}{$ext} = %File::Find::name;
}
}
my @list_of_directories = ();
# insert code to populate @list_of_directories
find( \&wanted, @list_of_directories );
for my $dir ( keys %Count ){
for my $ext ( keys %{ $Count{$dir} } ){
if( $Count{$dir}{$ext} > $N ){
# change to a real unlink command when script is debugged
print "unlink $Oldest{$dir}{$ext};\n";
}
}
}
__END__
BTW, you should defined by what you mean by oldest. In the above, oldest
means oldest last modified.
--
__END__
Just my 0.00000002 million dollars worth,
--- Shawn
"For the things we have to learn before we can do them, we learn by
doing them."
Aristotle
* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is at http://perldoc.perl.org/
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>