我必须找到文件中的单词出现的次数,无论是大写还是小写。我用了 我的%数;
foreach my $line ( split "\n", $text )
{
foreach my $word ($line =~ /(\w+)/g)
{
$count{$word}++;
}
}
print "'love' occurs $count{myword} times\n";
我认为(\ w +)会大写和小写,但事实并非如此。我知道当我在散列中添加值时我应该改变这种情况,但是当我这样做时,我仍然没有得到正确的答案。
答案 0 :(得分:3)
\w
匹配大写和小写(以及0-9和下划线)。 lc是忽视案件的一种方式。
use warnings;
use strict;
my $text = '
Here are words to count.
Words. And now more words.
';
my %count;
while ($text =~ /(\w+)/g) {
$count{lc $1}++;
}
use Data::Dumper;
$Data::Dumper::Sortkeys=1;
print Dumper(\%count);
__END__
$VAR1 = {
'and' => 1,
'are' => 1,
'count' => 1,
'here' => 1,
'more' => 1,
'now' => 1,
'to' => 1,
'words' => 3
};