: I want to count words from a file. For example how many times appears the word "example" in a file. I thougth to use grep, but grep only counts the lines (if in the same line appears more than one "example" doesn't count as 2).
: Is there a simple way to do that?
: I don't mind if it is in another language (not in Perl).
: Thanks
:
Use a hash: use the word as the hash key and increment the value in the hash every time we see the word. The print the list out at the end.
#!/usr/bin/perl
# Hash.
my %wordcount;
# Go through each line in the file.
open FILE, "< thefile.txt";
while (my $line = <FILE>) {
# Remove non-word characters.
$line =~ s/[^\w\']//g;
# Split and increment hash count for each word.
$wordcount{$_}++ for split(/\s+/, $line);
}
close FILE;
# Print word count list.
print "$_: $wordcount{$_}\n" for sort keys %wordcount;
Getting the count for an individual words is easy too.
Have fun,
Jonathan
###
for(74,117,115,116){$::a.=chr};(($_.='qwertyui')&&
(tr/yuiqwert/her anot/))for($::b);for($::c){$_.=$^X;
/(p.{2}l)/;$_=$1}$::b=~/(..)$/;print("$::a$::b $::c hack$1.");