Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Do Perl exercise 1 using a hash instead of an array. Include the source code of

ID: 3845262 • Letter: D

Question

Do Perl exercise 1 using a hash instead of an array. Include the source code of your program in perl_assignment.txt.

code:

# perlex1.pl: count word lengths in english.sorted

#1 - Read each line from english.sorted
while( $word = <STDIN>)
{
   #2 - Get length of each word that we read
   $length = length($word); # Subtract 1 for included newline char
   #3 - Increment correct word length array element using $length
   $wordlength[$length]++; # @wordlength array created on the fly
}

# 4 - Print the word length array elements
print "Word length Occurrences ";

for ( my $i = 1; $i <= $#wordlength; $i++)
{
   if (not exists $wordlength[$i])
   {
       print"$i 0 ";
       continue;
   }
   else{
   print "$i $wordlength[$i] ";
   }

}

Explanation / Answer

The given code with HASH:-

while( $word = <STDIN>)
{
   $length = length($word)
   $wordlength{$length}++;
}

print "Word length Occurrences ";

foreach my $word ( keys %wordlength) {

print "$word $wordlength{$word} ";

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote