Reputation: 11
I have to find how many times a word in a file appears, whether it is upper or lower case. I used:
my %count;
foreach my $line ( split "\n", $text )
{
foreach my $word ($line =~ /(\w+)/g)
{
$count{$word}++;
}
}
print "'love' occurs $count{myword} times\n";
I thought that (\w+)
would get upper and lowercase, but it did not. I know I should alter the case when I add the value in the hash, but when I do, I still do not get the right answer.
Upvotes: 1
Views: 154
Reputation: 62096
\w
does match upper and lower case (and 0-9 and the underscore). lc is one way to disregard case.
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
};
Upvotes: 3