#! /usr/bin/perl -w
use strict;

# print all the unique lines in a file

# check the script was invoked correctly, end if not
my $args = scalar @ARGV;
if ($args != 1) {
   print "correct use is $0 filename\n";
   exit 0;
}

# get the filename from the command line argument
my $filename = $ARGV[0];

# open the file or generate a message indicating you couldn't
open(INFILE, "$filename")
   or die "unable to open file $filename\n";

# let the user know what will be displayed
print "displaying all unique lines in file \'$filename\'\n";

# go through the lines one at a time until end of file
#    displaying the unique lines,
# using a hash table to store a count of how often
#    the line appears
my %lines;
while (<INFILE>) {
  # this is the first instance if the line is not
  #    yet in the hash table,
  # in which case we print it and add it to the hash table
  my $curLine = "$_";
  if (exists($lines{'$curLine'})) {
     $lines{'$curLine'} += 1;
  } else {
     print "$curLine\n";
     $lines{'$curLine'} = 1;
  }
}

# close the file
close(INFILE);

# print each line and its frequency
my $key;
print "frequency of each line:\n";
foreach $key (keys %lines) {
   my $val = $lines{$key};
   print "   $val: $key\n";
}

