I'm writing a perl script where a should process the text and then provide the dictionary with word frequences and then sort the dictionary. The text is an extract from "Golden Bug" by Edgar Poe and the purpose is to calculate frequences of all of the words. But I do smth wrong because I get no output. When am I doing wrong? Thanks.
open(TEXT, "goldenbug.txt") or die("File not found");
while(<TEXT>)
{
chomp;
$_=lc;
s/--/ /g;
s/ +/ /g;
s/[.,:;?"()]//g;
@word=split(/ /);
foreach $word (@words)
{
if( /(\w+)'\W/ )
{
if($1 eq 'bug')
{
$word=~s/'//g;
}
}
if( /\W'(\w+)/)
{
if(($1 ne 'change') and ($1 ne 'em') and ($1 ne 'prentices'))
{
$word=~s/'//g;
}
}
$dictionary{$word}+=1;
}
}
foreach $word(sort byDescendingValues keys %dictionary)
{
print "$word, $dictionary{$word}\n";
}
sub byDescendingValues
{
$value=$dictionaty{$b} <=> $dictionary{$a};
if ($value==0)
{
return $a cmp $b
}
else
{
return $value;
}
}
You have in your code:
@word=split(/ /);
foreach $word (@words)
{
You've named the array as @word
during the split but you are using the array @words
in the for loop.
@word=split(/ /);
should be
@words=split(/ /);
Another typo in the byDescendingValues
routine:
$value=$dictionaty{$b} <=> $dictionary{$a};
^^
As suggested in other answer, you really should add
use strict;
use warnings;
Using these you could have easily caught these typos. Without them you'll be wasting lot of your time.