Archive for January, 2009

Program to count number of words in a file


#!/usr/bin/perl

sub count_words_in_line {
  # use our to declare global variable.
  our %word_count;

# below two lines can be combined into one like this - @words = split " ", shift
  $line = shift @_;
  @words = split " ", $line;

  foreach my $word (@words) {
    $word_count{$word}++;
  }

}

sub count_words_in_file {
  my $file = shift;
  print $file . "\n";
  open (FILE, $file) || die "$0: @_: $!";

  while (my $line = ) {
    count_words_in_line $line;
  }

}

#print @ARGV[0] . "\n";

$file_name = shift;
count_words_in_file $file_name;

print %word_count;

Comments (1)

Word Frequency Counter in Perl



#!/usr/bin/perl

use strict;

my @sentence = qw(Bha Bha Black Sheep);
my $sentence_length = @sentence;

my %word_count;

for my $word (@sentence)
{
  $word_count{$word}++;
}

print %word_count;

Leave a Comment