#! /usr/bin/perl

sub fileCount($$);

# fileCount(extensionsHash, directory)
# ------------------------------------
# given a hash whose keys are a set of file extensions,
#   and a directory to examine,
# count the number of files with each extension,
#   setting the associated hash value
# returns a count of the number of files in the specified directory
#    that have the specified file extension
sub fileCount($$)
{
  my $extHash = $_[0];
  my %extensions = %$extHash;
  my $directory = $_[1];

  print "searching dir $directory\n";

  # if the directory cannot be opened then terminate early
  opendir (my $handle, $directory)
     or die "Error: could not open directory $directory\n";

  # read the directory contents, checking each file against each extension
  while ( readdir $handle ) {
     my $nextfile = $_;
     print "counting file $nextfile\n";
     # compare the current file to each of the extensions
     foreach my $extension (keys %extensions) {
        my $pattern = "\\.$extension\$";
        print "   Comparing $extension to pattern $pattern\n";
        # if the file has the desired extension,
        #    increment the count for that extension
        if ($nextfile =~ $pattern) {
           $extensions{$extension} = $extensions{$extension} + 1;
        }
     }
  }
  closedir $handle;

  return \%extensions;
}

my %ext = ( 'pl', 0, 'cpp', 0, 'html', 0, 'sh', 0 );
my $dir = '.';
my $result = fileCount(\%ext, $dir);
my %extHash = %$result;
foreach my $e (keys %extHash) {
   my $c = $extHash{$e};
   print "file ext: $e, file count $c\n";
}

1;

