wc: Word Count

The goal for this Programming Praxis was to implement the Unix wc function. This one took me a couple days (I haven’t had a lot of time recently) to complete, but I finally finished it and this it works pretty good. It’s not a drop in replacement for wc, but it works – a programmers solution: by programmers, for programmers.

<br />
use Switch;</p>
<p>#print &quot;arg num &quot;. $#ARGV;<br />
if ($#ARGV == -1) {<br />
	usage();<br />
}</p>
<p>@option;<br />
@input;</p>
<p>#check first char of each argument<br />
foreach $arg (@ARGV){<br />
	if($arg =~ m/-.*/){<br />
		@option = split //, $arg;<br />
		#print &quot;!&quot;.$arg.&quot;\n&quot;;<br />
	}<br />
	else{<br />
		push(@input, $arg);<br />
	}<br />
}<br />
#remove the &quot;-&quot; from the array<br />
shift(@option);</p>
<p>foreach $input (@input){</p>
<p>	if(-e $input){<br />
	#file exists, continue<br />
		local( *FH ) ;<br />
		open( FH, $input ) or die &quot;sudden flaming death\n&quot;;<br />
		$file = do { local( $/ ) ; &lt;FH&gt; };<br />
		$fileSize = (-s $input);<br />
		close(FH);<br />
	}else{<br />
		die(&quot;No such file or directory&quot;);<br />
	}<br />
	print &quot;$input &quot;;<br />
	foreach $flag (@option){<br />
		switch ($flag){</p>
<p>			case &quot;c&quot; {print &quot;$fileSize &quot;}<br />
			case &quot;m&quot; {print length($file) . &quot; &quot;}<br />
			case &quot;l&quot; {print $file =~ s/((^|\s)\S)/$1/g .&quot; &quot;}<br />
			case &quot;L&quot; {print maxLineLength($input).&quot; &quot;}<br />
			case &quot;w&quot; {print $file =~ s/(\n)/$1/g . &quot; &quot;}<br />
			else {die (&quot;invalid option -- $flag&quot;)}<br />
		}<br />
	}<br />
	print &quot;\n&quot;;<br />
}</p>
<p>sub maxLineLength($input){<br />
	my($thisInput) = @_;<br />
	open(FH, $thisInput);<br />
	$maxLine = 0;<br />
	foreach $line (&lt;FH&gt;){<br />
		if(length($line) &gt; $maxLine){<br />
			$maxLine = length($line);<br />
		}<br />
	}<br />
	return $maxLine;<br />
}</p>
<p>sub usage{</p>
<p>	print &quot;Usage: wc [OPTION]... [FILE]...\n&quot;;<br />
	print &quot;  or:  wc [OPTION]... --files0-from=F\n&quot;;<br />
	print &quot;Print newline, word, and byte counts for each FILE, and a total line if\n&quot;;<br />
	print &quot;more than one FILE is specified.  With no FILE, or when FILE is -,\n&quot;;<br />
	print &quot;read standard input.\n&quot;;<br />
	print &quot;  -c            print the byte counts\n&quot;;<br />
	print &quot;  -m            print the character counts\n&quot;;<br />
	print &quot;  -l            print the newline counts\n&quot;;<br />
	print &quot;  -L, --max-line-length  print the length of the longest line\n&quot;;<br />
	print &quot;  -w, --words            print the word counts\n&quot;;<br />
}</p>
<p>