Counting frequency of all words of a string is a basic operation for any programming language. The frequency of each word of the text can be counted and stored in a hash for further use. In Perl, we can do this by firstly splitting the words of the string into an array. We use the function split / / which splits the string with ‘ ‘. However the blank spaces can be more than one in between two words, therefore /\s+/ is used. Here \s+ denotes one or more occurrence of ‘ ‘. Now we traverse the new array created by splitting of text into words. This time we increment the count of the word while traversing the array.
- Example: To demonstrate Count the frequency of words in string
$actual_text = "GFG GeeksforGeeks GFG" ;
@words = split / /, $actual_text ;
foreach $word ( @words )
{
$count { $word }++;
}
foreach $word ( sort keys %count )
{
print $word , " " , $count { $word }, "\n" ;
}
|
Output:
GFG 2
GeeksforGeeks 1
Difference between /\s+/ and / /: The ‘\s+’ can be used for a delimiter with one or many space. However / / just separates words with 1 space. The following code represents the difference if the text has more than one space between two words.
Using the command /\s+/ to split the words: Here space will not count as the separate word.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
12 Feb, 2019
Like Article
Save Article