如何以perl方式添加搜索功能?

时间:2011-10-11 04:07:22

标签: perl

here获得建议后。我将代码更改为:

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";
}

现在我希望在此代码中添加搜索功能。例如,如果我使用<STDIN>从用户那里获得搜索关键字,那么在该关键字的帮助下我如何找到给定文本文件中的搜索词数(我将传递给代码)?

由于我是Perl的新手,我需要更多的Perl方法来实现这一点。

提前致谢。

3 个答案:

答案 0 :(得分:1)

您可以尝试:

   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};

答案 1 :(得分:0)

您可以重复使用%words hash来检查关键字的存在和总数。 您可以在读取文本文件并填充%字后添加此代码。

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";
}

答案 2 :(得分:0)

您可以这样做:

chomp (my $keyword = <STDIN>);
if(exists($words{$keyword}))
{
        print "The word $keyword occured $words{$keyword}";
}
else
{
        print "The word  $keyword doen't occur sorry!";
}

请参阅here,主题为:测试哈希中是否存在密钥

希望这会有所帮助。