#!/usr/local/bin/perl ######################################################################### # Name: Bridget Thomson-McInnes # Program: count.pl ######################################################################### # Program Description: # Determines the number of characters, words or lines in a directory # of text files or a specified file. # # Usage: # For character count: ./count.pl character [y|n] # For word count : ./count.pl word [y|n] # For line count : ./count.pl line # # [y|n] : (default n) # y = complete print out # n = only totals ########################################################################## $complete = "bugger"; $tokens = 0; @files = (); my($input, $routine, $complete) = @ARGV; if(-d $input) { $dirpath = $input; @temp = (); opendir(THISDIR, $dirpath) || die "Can not open the $dirpath"; push(@temp, grep {$_=~/txt/ } readdir THISDIR); closedir THISDIR; foreach (@temp) { push @files, $dirpath . "/" . $_; } } else { push @files, $input; } format STDOUT = @<<<<<<<<<<<<<<<<<<<<<<<<<<< @########## $item, $freq . foreach $file (@files) { open(FILE, $file) || die "Can not open file: $file\n"; while() { chomp; s/^\s+//; s/\s+$//; if($routine eq "character") { s/\s+//g; @array = split//; } elsif($routine eq "word") { @array = split/\s+/; } if($routine eq "line") { $hash{line}++; } foreach (@array) { $hash{$_}++; $tokens++; } } } $types = 0; foreach $item (sort { $hash{$b} <=> $hash{$a} } keys %hash) { $freq = $hash{$item}; $types++; if($complete eq 'y') { write; } if($routine eq "line") { write; } } if($routine ne "line" and $routine ne "file") { print "Total tokens: $tokens\n"; print "Total types: $types\n"; }