0
  1. Reads a sentence from the user using the <> operator, splits the sentence into an array of words (hint: use split(/regex/, $string), and outputs how many words there are in the sentence.

  2. Creates a hash which contains words from the sentence as keys and the number of occurrences of each word as the associated value and prints out the number of occurrences of each word in the sentence in alphabetical order.

Ok, so the above question was given to me as an assignment! and before you think I am going to ask for one to solve it, i'm not i'm simply looking for some guidance on how to complete it!

I have completed the first part which was actually pretty easy! it will paste it down below:

print("please enter a sentence!\n");
$x = <>;
chomp $x;

@bases=split(" ",$x);
print ("@bases\n");
foreach $i (@bases){
  print("$i\n");
}

$size=@bases;
print("the amount of words in this sentence are:$size\n");

I understand what the second question is asking me to do, however i'm having trouble implementing it! how on earth does one count how many time a word repeats in a sentence and then use it as the value to that exact word! i just don't know! so maybe if some one ANYONE can guide me on the right tracks! I'd be so appreciative!

thank you! if I figure any more of it out i'll paste it!

2

1 Answer 1

0

Think of a hash as an array whose subscripts (called "keys") are not limited to being integers. In this problem, the keys would naturally be the words your script processes, and the hash values would be the number of occurrences for each key. So every time you find a word, use that as the hash key, incrementing the hash value by one.

To print the result in alphabetic order, you would construct a sorted array of all of the hash keys, and make a loop (whether foreach or for depends on taste), printing each hash key and the corresponding hash value.

Since it is an exercise, you have to find how to express that in code.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .