Thread: perl program question

  1. #1
    newbie2c
    Guest

    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.

  2. #2
    Registered User Cela's Avatar
    Join Date
    Jan 2003
    Posts
    362
    >>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? :-)
    *Cela*

  3. #3
    Registered User Vber's Avatar
    Join Date
    Nov 2002
    Posts
    807
    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
    Last edited by Vber; 02-03-2003 at 10:29 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Question regarding a this C program
    By cnb in forum C Programming
    Replies: 10
    Last Post: 10-11-2008, 04:43 AM
  2. newb question: probs with this program
    By ajguerrero in forum C Programming
    Replies: 5
    Last Post: 04-19-2006, 08:04 AM
  3. Random Question Assign Program
    By mikeprogram in forum C++ Programming
    Replies: 6
    Last Post: 11-17-2005, 10:04 PM
  4. Replies: 26
    Last Post: 06-15-2005, 02:38 PM
  5. Replies: 8
    Last Post: 03-26-2002, 07:55 AM