In: Computer Science
Write a program named "cleanDocument.pl" that will do the following:
Below is an example of how the program works:
Calling the Perl file on the command line like so:
$ cleanDocument.pl document.txt bobsled
or
$ cleanDocument.pl $ What file do you want to open? document.txt $ What word do you want to replace? bobsled
If the file looks like below:
$ cat document.txt I like to use my bobsled during the winter. Whenever I bobsled I have a lot of fun.
Then it will be become:
$ cat document.txt I like to use my ------- during the winter. Whenever I ------- I have a lot of fun.
Given question, let us implement following points in question as cleanDocument.pl, Below is Solution perl cleanDocument.pl snippet with detailed explaination using comments,
use warnings;
# take input argument file name and word to replace
my ($fileName, $word) = @ARGV;
if(not defined $fileName)
{
# request file name to user as specified in question.
print "What file do you want to open? ";
$fileName = <STDIN>;
# Remove new line end of input
chomp $fileName;
}
if(not defined $word)
{
# as specified in question prompt user to enter word name
print "What word do you want me to replace? ";
$word = <STDIN>;
chomp $word;
}
@newLines = ();
# open file, throw error and exit if no file exist
open(my $fhr, '<', $fileName) or die "file '$fileName' not present $!\n";
while (my $file_data = <$fhr>)
{
chomp $file_data;
# for word replacement with equal number of dashes
$word_replacement = "-" x length($word);
if($file_data =~ m/$word/)
{
# if string matches with specified word,
# replace word with word_replacement store in file_data variable.
$file_data =~ s/$word/$word_replacement/g;
}
# write newLines with new file data
push @newLines, $file_data;
}
open(my $fhw, '>', $fileName) or die "Could not open file '$fileName' $!\n";
# for each new lines, wite file with modified lines
for(@newLines)
{
print $fhw "$_\n";
}
Output:
Test for no command line parameters,