Pass each directory as a parameter to the script. This can be wrapped in a shell loop if you want to.

#!/usr/bin/perl -w

use Data::Dumper;
use File::Find;
use File::stat;
use List::Util qw(sum min max);

my %files;
my $root_dir = $ARGV[0];
my $min_file_size = ‘1’; # bytes

#================================================================
#- Main
#================================================================
#
&find_files;
&create_and_print_output;

#print Dumper %files;

#================================================================
#- Find all files and their info so that we can
# find average file size.
#================================================================
#
sub find_files {
print “\nTraversing tree $root_dir…\n\n”;
find(\&trav_tree, “$root_dir” );
}

#================================================================
#- Traverse dir tree for sub find_file and
# store file info in data structure
#================================================================
#
sub trav_tree {
if ( -e $File::Find::name ) {
$files{ ‘files’ }->{ total } += 1;
push @{ $files{ ‘files’ }->{ sizes } }, stat($File::Find::name)->size;

if ( stat($File::Find::name)->size >= $min_file_size ) {
$files{ ‘sizes’ }->{ stat($File::Find::name)->size }->{ filename } = $File::Find::name;
}
}
}

#================================================================
#- Create and print output
#================================================================
#
sub create_and_print_output {
my $sum = sum( @{ $files{ ‘files’ }->{ sizes } } );
my $number_of_files = $files{ ‘files’ }->{ total };
my $average_file_size = $sum / $number_of_files;
my $smallest_file_name = $files{ ‘sizes’ }->{ min ( keys %{ $files{ ‘sizes’ } } ) }->{ filename };
my $smallest_file_size = min ( keys %{ $files{ ‘sizes’ } } );
my $biggest_file_name = $files{ ‘sizes’ }->{ max ( keys %{ $files{ ‘sizes’ } } ) }->{ filename };
my $biggest_file_size = max ( keys %{ $files{ ‘sizes’ } } );

printf “Number of files: %d\n”, $number_of_files;
printf “Avergae file size: %d bytes\n\n”, $average_file_size;

printf “Smallest file found was %s with a size of %d bytes\n”, $smallest_file_name, $smallest_file_size;
printf “Biggest file found was %s with a size of %d bytes\n\n”, $biggest_file_name, $biggest_file_size;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s