After getting suggestion's from here. I changed my code as :
开发者_运维问答my $lineCount=0;
while (my $line = <>){
for (split /\s+/, $line)
{
$words{$_} ++;
}
print "Interpreting the line \t $line\n";
$lineCount++;
}
foreach $k (sort keys %words) {
print "$k => $words{$k}\n";
}
foreach $k (sort keys %words) {
$count = $count+$words{$k};
}
print "the total number of words are $count. \n";
$test = scalar(keys %words);
print "The number of distinct words are $test. \n";
print "The number of line is $lineCount. \n";
print "The word distribution is as follows \n";
my %lengths;
$lengths{length $_} += $words{$_} for keys %words;
foreach $k (sort keys %lengths) {
print "$k => $lengths{$k}\n";
}
Now I wish to add the search functionality in this code. Example if I get search keyword from the user using <STDIN>
, then with the help of that keyword how I can find the number of search word in the given text file(which I'm passing to the code)?
Since I'm a novice in Perl, I need a more Perl way of doing this.
Thanks in advance.
You can try:
my $lineCount = 0;
my %lengths;
while (<>){
for (split /\s+/) {
$words{$_}++;
}
print "Interpreting the line \t $_\n";
$lineCount++;
}
foreach (sort keys %words) {
print "$_ => $words{$_}\n";
$count = $count+$words{$k};
}
my $test = scalar(keys %words);
$lengths{length $_} += $words{$_} for keys %words;
# Output Results
print <<"END";
The total number of words are $count.
The number of distinct words are $test.
The number of lines is $lineCount.
The word distribution is as follows:
END
foreach (sort keys %lengths) {
print "$_ => $lengths{$_}\n";
}
#Get user input
my $input = <STDIN>;
chomp $input;
print "$input: $words{$input} matches\n" if $words{$input};
You can do something like this :
chomp (my $keyword = <STDIN>);
if(exists($words{$keyword}))
{
print "The word $keyword occured $words{$keyword}";
}
else
{
print "The word $keyword doen't occur sorry!";
}
See here, under the topic : Testing for the Presence of a Key in a Hash
Hopes this helps.
You can reuse the %words hash to check for the existence and the total count of the keywords. You can add this code after the text file is read and %words is populated.
my $msg = "Enter keyword (Ctrl+d on Unix or Ctrl+Z on Windows for none): ";
print "\n$msg";
while ( chomp (my $keyword = <STDIN>) )
{
#check if the keyword exists in %words.
if ( my $total_keyword = $words{$keyword} )
{
print "\nTotal number of the keyword $keyword is - $total_keyword\n";
}
print "\n$msg";
}
精彩评论