user1739860
user1739860

Reputation:

Printing frequency of words in Perl

I'm new to Perl and I'm currently writing a program to display words given by user input and the frequency of the words. I believe I have all the functions set properly I am just having trouble displaying the words and their frequency (I believe it has to do with my hash values). An example of an input would be : hello hello how are are you. and I'd like it to be displayed as: hello = 2 how = 1 are = 2 you = 1

#!usr/bin/perl -w 
 use strict;
 my @User_Input = <STDIN>;
 chomp(@User_Input);

 my $Word;
 my $Word_Count = 0;
 my %Word_Hash;

foreach $Word (@User_Input)
{
        #body of loop

         my @lines = split(/\s+/, $Word);
         $Word_Count = scalar(@lines);

        if (exists($Word_Hash{$Word}))
        {
                keys(%Word_Hash);
                my @all_words = keys(%Word_Hash);

        }

}

Upvotes: 1

Views: 3433

Answers (2)

Vijay
Vijay

Reputation: 67281

perl -lane '$X{$_}++ for(@F);END{for(keys %X){print $_." ".$X{$_}}}'

tested:

> echo "hello hello how are you you" | perl -lane '$X{$_}++ for(@F);END{for(keys %X){print $_." ".$X{$_}}}'
you 2
how 1
hello 2
are 1
> 

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 754280

Avoid slurping files when you don't need everything in memory, so your @User_Input = <STDIN>; is not a particularly good idea. You can perfectly well process this all one line at a time:

#!/usr/bin/env perl
use strict;
use warnings;

my %words;

while (my $line = <>)
{
    foreach my $word (split /\s+/, $line)
    {
        $words{$word}++;
    }
}

foreach my $word (keys %words)
{
    print "$word: $words{$word}\n";
}

Sorting the data is a bit fiddlier, but can be done.

Upvotes: 2

Related Questions