Reputation: 51
my $line = "The quick brown fox jumps over the lazy dog.";
while ($line =~ /(\w+)\s(?=(\w+\b))/g) {
print("$1 $2\n");
}
**So far this will output The quick quick brown brown fox....
Is there a way to output a text file that also includes word count for example: The quick: 3 (times of occurrence) quick brown:2 brown fox:5...
Maybe we can use something like
$wordcount{$word} += 1;
but of course any plausible solutions are welcomed and thank you guys very much. P.S. apologies for the vague expression since I am a super beginner.
**
Upvotes: 1
Views: 86
Reputation: 117298
You could use a hash that maps the word pair (key) to the number of occurrences (value).
Example:
#!/bin/perl
use strict;
use warnings;
my $line = "The quick brown fox jumps over the lazy dog.";
my %paircount;
while ($line =~ /(\w+)\s+(?=(\w+\b))/g) {
# put the word pair in the map and increase the count
$paircount{"$1 $2"}++;
}
# print the result
while(my($key, $value) = each %paircount) {
print "$key : $value time(s)\n";
}
Possible output:
fox jumps : 1 time(s)
lazy dog : 1 time(s)
over the : 1 time(s)
the lazy : 1 time(s)
brown fox : 1 time(s)
jumps over : 1 time(s)
quick brown : 1 time(s)
The quick : 1 time(s)
Upvotes: 3