[Chicago-talk] array to hash and counting files

Randal L. Schwartz merlyn at stonehenge.com
Tue Dec 30 11:07:43 CST 2003


>>>>> "Jeremy" == Jeremy Hubble <jhubble at core.com> writes:

Jeremy> I have a series of directories that each have a number of 
Jeremy> subdirectories with the same directory structure.  I need to count the 
Jeremy> number of files and directories in each subdirectory, and get a list of 
Jeremy> all unique files.

Jeremy> Here is the code fragment I have (not tested yet):

Jeremy> Is there a more effecient way to:
Jeremy> 1) Extract the unique list of files?
Jeremy> 2) Use perl to replace the find commant?

Jeremy> Thanks,

Jeremy> Jeremy

Jeremy> my $d_count=0;
Jeremy> my $f_count=0;
Jeremy> my %map;
Jeremy> opendir (ED_DIR, $bdir);
Jeremy> @subdir = { /!^\./ && -d "$bdir/$_" } readdir(DIR);
Jeremy>         foreach $d (@subdir) {
Jeremy>                 chomp $d;
Jeremy>                 my $dir = "$bdir/$d";
Jeremy>                 my @files = qx~find $bdir -type 'f' -print~;
Jeremy>                 my @dirs = qx~find $bdir -type 'd' -print~;
Jeremy>                 $d_count+=$#files+1;
Jeremy>                 $f_count+=$#dirs+1;
Jeremy>                 foreach $f (@files) {
Jeremy>                       $map{$f} = 1;
Jeremy>                 }
Jeremy>         }

If I understand you, I think this will do it:

my $d_count = 0;
my $f_count = 0;
my %unique_files;

use File::Find;
find sub {
  if (-d $_) {
    $d_count++;
  } elsif (-f _) {
    $f_count++;
    # remove prefix:
    (my $n = $File::Find::name) =~ s/^.*?\//;
    $unique_files{$n} = 1;
  }
}, $bdir;


-- 
Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
<merlyn at stonehenge.com> <URL:http://www.stonehenge.com/merlyn/>
Perl/Unix/security consulting, Technical writing, Comedy, etc. etc.
See PerlTraining.Stonehenge.com for onsite and open-enrollment Perl training!



More information about the Chicago-talk mailing list