#!/usr/bin/env perl -w use strict; if (!@ARGV){ #no command line arguments, so Part A my ($file, $dir, $yn, @all_lines); #prompt for file name and attempt to open print "Enter the name of a file, please:\n"; chomp ($file = ); if (!-e $file){ #file does not exist in this directory print "$file does not exist in the current directory\n"; print "Do you wish to enter a directory where the file can be found? (y/n)\n"; chomp ($yn = ); if ($yn eq "n"){ #user doesn't wish to enter directory print "You've chosen not to enter a directory. Good bye\n"; exit; } #if we got here, user does want to enter a directory. Take it, and open file print "Enter the name of the directory (no trailing slash):\n"; chomp ($dir = ); open FILE, "$dir/$file" or die "Cannot open file: $!\n"; } else { # the file does exist, so open it. open FILE, "$file" or die "Cannot open file: $!\n"; } # file is opened (one way or another). Read from it now and print the info @all_lines = ; print "The file $file contains " . @all_lines . " lines\n"; if (@all_lines){ print "The first line is:\n"; print $all_lines[0]; print "The last line is: \n"; print $all_lines[-1]; } #Now we want to open a file in the same directory as the original #The new file's name is the old file name in all caps if ($dir){ # if we entered a directory name open OFILE, ">$dir/\U$file\E" or die "Cannot create \U$file\E: $!\n"; } else { open OFILE, "> \U$file\E" or die "Cannot create \U$file\E: $!\n"; } #now we simply print all lines of the original to the new (in lowercase) #since we're interpolating, elements will be printed with a space #seperating them. We don't want that. $" = ''; print OFILE "\L@all_lines\E"; #close both files close OFILE; close FILE; } else { #there was at least one command line argument, so Part B my ($word, @words, %words, $file, $line); foreach $file (@ARGV){ # go through each file and open it if (!open FILE, $file){ print "Cannot open $file: $!\n"; next; } foreach $line (){ #split each line in the file into words chomp $line; @words = split / /, $line; foreach (@words){ #use a hash to keep track of which words have been counted $words{$_}++; } } close FILE; } foreach $word (keys %words){ #go through each element of the hash print "$word - $words{$word}\n"; } if (keys %words == 0){ print "All files were empty or invalid\n"; } }