#!/usr/bin/env perl -w use strict; if (!@ARGV) { #no command line arguments, do part A my ($dir, @files, $num, @lines); print "Please enter a directory name: \n"; chomp ($dir = ); if (!(-e $dir && -d $dir)){ #if directory does not exist, or is not a directory print "Sorry, that is not a valid directory, exiting program\n"; exit; } opendir DIR, $dir or die "Cannot open directory $dir: $!\n"; @files = readdir DIR; print "There are " . @files . " in directory $dir, and they are:\n"; for (my $i = 0; $i < @files; $i++){ print "File #" . ($i + 1) . ": $files[$i]\n"; } print "Which file do you wish to open? (Enter a number from 1 to " . @files . ")\n"; chomp ($num = ); if ($num < 1 or $num > @files) { print "Sorry, that is not a valid number. Exiting.\n"; exit; } if (-d $files[$num-1]){ print "Sorry, $files[$num-1] is a directory, not a file\n"; exit; } open FILE, "$dir/$files[$num-1]" or die "Could not open file $files[$num-1]: $!\n"; @lines = ; close FILE; if (@lines % 2 == 0) { #if there are an even number of lines... print "The middle lines are:\n"; print $lines[(@lines / 2) - 1]; print $lines[@lines / 2]; } else { #there are an odd number of lines print "The middle line is: \n"; print $lines[@lines / 2]; } open AFILE, ">>$dir/$files[$num-1]" or die "Cannot open $files[$num-1] for appending: $!\n"; print AFILE "\U$lines[0]$lines[-1]\E"; close AFILE; print "$files[$num-1] has been updated\n"; } else { #Part B my (@words, %words); die "Incorrect number of command line arguments\n" if @ARGV != 2; if ($ARGV[1] ne "sort" && $ARGV[1] ne "count" && $ARGV[1] ne "both"){ die "Invalid option for second argument\n"; } open FILE, "$ARGV[0]" or die "Cannot open file $ARGV[0]: $!\n"; foreach (){ #iterate through the entire file chomp; @words = split / /; #create an array of words from this line foreach (@words){ #if this word is already in the hash, increment its value #otherwise, we're incrementing 'undef', which results in #the value 1, marking the first time the word has been #seen in the hash $words{$_}++; } } if ($ARGV[1] eq "count" or $ARGV[1] eq "both"){ # Now we print the counting foreach (keys %words){ print "Number of times '$_' appeared in $ARGV[0]: $words{$_}\n"; } } print "\n"; if ($ARGV[1] eq "sort" or $ARGV[1] eq "both"){ print "All words in $ARGV[0] in sorted order:\n"; $, = "\n"; print (sort keys %words, "\n"); } }