Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

simple perl problem - counting strings?

Status
Not open for further replies.

mkosloff

Programmer
Feb 20, 2003
12
US
I am writing a program that takes a file, reads all the words as lower case, and then prints alphabetically the list of the all the words used, and the frequency of how often they appear in the program. i am using a simple file with just this:

You like this
you cant wait to do this

And I need the output to be:

"--- Word Count ---"
cant 1
do 1
like 1
this 2
to 1
you 2

Is there a simple function call that allows me to keep track of how often words are used? Below is my code. If someone can let me know if I'm on the right track, or if there is a simple tool I am unaware of, I'd really appreciate it. Thanks!

---------------

open(TT, $ARGV[0]) or die "Can't open $ARGV[0]. \n";

@lines = <TT>;
close(TT);



@ary = split / /, $lines[$i];
@ary = lc @ary;
@ary = sort @ary;

print &quot;----\tWord \t Count ----\n&quot;;
print &quot;$ary[0]\n&quot;;
for ($i =0; $i <=$#ary; $i++)
{
$tmp[$x] = lc ($ary[$i]);
if ($tmp[$x] == $tmp[$x-1])
{
$x++;
}
}

exit (0);
 
You are on the right lines, but there are few Perl functions that do make life easier for you.


open(TT, $ARGV[0]) or die &quot;Can't open $ARGV[0]. \n&quot;;
my @lines = <TT>;
close(TT);

# join lines, then split on whitespace (includes \n)
my @words = split /\s+/, lc(join(&quot;&quot;,@lines));

# build word counter hash
my %wc = ();
foreach my $word (@words) { $wc{$word}++ }

print &quot;----\tWord \t Count ----\n&quot;;

# sort hash keys into order and print
foreach my $word (sort {$a cmp $b} keys %wc) {
print &quot;\t$word\t$wc{$word}\n&quot;;
}


Barbie
Leader of Birmingham Perl Mongers
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top