-
perl program question
Hi, I am trying to make a word frequency counter using PERL.
Basically, I need to read in a text file and print out to stdout a list of all the unique words in the file and how many times they appear in descending order. I am new to PERL and just got this program working in C by using a binary search tree someone on this board suggested. :-)
I was wondering if anyone could tell me if binary trees and linked lists can be created in PERL or what anyone thinks would be the best way of implementing this program in PERL?
Any ideas would be greatly appreciated.
Thanks.
-
>>what anyone thinks would be the best way of implementing this program in PERL?
Get used to thinking in hashes :-)
Code:
#!/usr/bin/perl -w
use strict;
my %frequency;
while (<>) {
s/\W+\s|\W+$/ /g; # Removed extraneous punctuation
my @words = split /\s+/, $_; # Break up the words
# Increment the frequencies for each word
for (@words) {
$frequency{$_}++;
}
}
# Print :-)
for (sort keys %frequency) {
print $_, "\t-- ", $frequency{$_}, "\n";
}
Run this by saying
Code:
% script.pl wordfile.txt
>>I was wondering if anyone could tell me if binary trees and linked lists can be created in PERL
Yes, here's a quick and easy linked list that you'll probably never need since Perl arrays are so flexible :-)
Code:
#!usr/bin/perl -w
$head = undef;
for (1..5) {
$head = [$_, $head];
}
for (; defined $head; $head = $head->[1]) {
print $head->[0];
}
Binary trees really aren't any harder, isn't Perl nice? :-)
-
And you think this is a Perl board?
Hmm, can't see it's writed 'C Programming'?
Want a screenshot, or something?
Luck we have Cela here to answer not just C/C++/C# question, but perl too ;)