write a perl program that counts the number of files in the working directory and the number of bytes in those files by file name
Answers
Program Code:
$ cat getsize.pl
#!/usr/bin/perl
# program to count the number of files in the working directory and number of bytes in those files, by filename extension
use strict;
use warnings;
# initializing num_of_files to zero and ext_hash(extension hash) to empty list
my $num_of_files = 0;
my %ext_hash=();
# assigning initial value to 0 for the key * which we will use for files with no extension
$ext_hash{'*'} = 0;
opendir my $dir, '.' or die "could not open directory: $!";
# reading files in the current directory
while (my $entry = readdir $dir){
# skipping if the file name is '.' or '..'
next if($entry eq '.' || $entry eq '..');
chomp($entry);
# splitting filename and extension so we have filename in fname variable and extension of it in ext variable.
my ($fname, $ext) = split(/\./, $entry, 2);
# counting number of files in the working directory
$num_of_files++;
# if no extension is available for filename, we should add the byte count to key '*' which we use for files with no extension
if (not defined $ext){
$ext_hash{'*'} = $ext_hash{'*'} + get_byte_count($entry);
next;
}
# for files with extension we will create extensions as keys to sum the total bytes of all the files with that extension
if (exists $ext_hash{$ext}){
$ext_hash{$ext} = $ext_hash{$ext} + get_byte_count($entry);
}
else{
$ext_hash{$ext} = get_byte_count($entry);
}
}
closedir($dir);
print "
";
print "Extension\tCount
";
# printing the filename extension byte count
foreach my $ext (keys %ext_hash){
print ".$ext", "\t\t", $ext_hash{$ext}, "
";
}
print "
Total number of files in the working directory: $num_of_files";
print "
";
# Method to get the byte count for a given file
# will not work for directories
sub get_byte_count{
# fetching the filename passed to the function
my $fname = shift;
my $wc = 0;
# opening the file in read mode
open(FH, "$fname") or die "$fname not able to open: $!";
# Iterating through each line in file and summing byte count
while(){
# summing byte count to wc variable by getting length of each line
$wc += length $_;
}
close(FH);
return $wc;
}