#!/usr/local/bin/perl

# COMS3101 Perl Fall 2013
# hw1.pl

# Problem 2: build a hash
# -----------------------
# Hard-code an array:
@arr = ("Boston","Texas","Manchester","Paris","Amsterdam");
%hash = (); # initialize 

# Build hash using loop
foreach $city (@arr) {
   $hash{$city} = length($city); 
}

# Without loop 
# $hash{$_} = length foreach @arr; 

# Print each element and #characters
print "\nPROBLEM 2:\n";
foreach (@arr) {
   print "$_ : $hash{$_}\n"; 
}

# Problem 3: arrays and loops
# ---------------------------
# Hardcode @coeffs, $x
@coeffs = (3,0,4);
$x = 4;

# Evaluate the polynomial
# Print the result
# There are many correct solutions

$res = $exp = 0;
foreach (@coeffs) {
 $res += ($_ * ($x ** $exp));
 $exp++;
}

print "\nPROBLEM 3:\n";
print "Polynomial evaluates to : $res\n";

# Problem 4: hashes, subs
# ---------------------------

# The following code is not the shortest,
# but every step is very clear.

sub Word_Lookup {
   my $word = shift;
   my $lcw = lc($word);    	# lower case
   my $ucw = uc($word);	# upper case	

   # Assume %wh is a hash defined globally
   if (exists $wh{$lcw}) {
     return $wh{$lcw};
   }  
   elsif (exists $wh{$ucw}) {
     return $wh{$ucw}; 
   }
   else  {
     return "NIL";
   }
}

# Test code to verify sub
%wh = ("boston" => 4, "DALLAS" => 5,
       "dayton" => 3.4, "FRESNO" => 6,
       "newark" => 3 );

print "\nPROBLEM 4:\n";
print "Value : ", Word_Lookup("BosTon"), "\n";
print "Value : ", Word_Lookup("DALLas"), "\n";
print "Value : ", Word_Lookup("FrEsNo"), "\n";
print "Value : ", Word_Lookup("wrong"), "\n";


# Problem 5: input/output, sort
# -----------------------------

# Open file article.txt and read all lines
open INFILE, "article.txt" or die "could not read file\n"; 
my @lines = <INFILE>;
chomp @lines;
close INFILE;

# Split each line by space
# Populate a dictionary with counts
%wct = ();
foreach $line (@lines) {
    @words = split ' ', $line;
    foreach $word (@words) {
        $wct{$word}++;  
    }
}

# Array to hold sorted keys
# Not necessary (used here to make code more clear)
@skeys = sort {$wct{$b} <=> $wct{$a}} keys %wct;

# Create file wordcounts.txt
# List frequencies of words
open(OUTFILE, ">wordcounts.txt");
foreach $key (@skeys) {
    print OUTFILE "$key $wct{$key}\n"; }
# Instead of two lines can do this:
# print OUTFILE "$_ $wct{$_}\n" foreach @skeys;
close(OUTFILE); 

# Count unique words
$count = scalar (keys %wct);

# Top word (sort hash by value)
$tword = $skeys[0]; 

# Print the number of unique words
# Print word with highest frequency
print "\nPROBLEM 5:\n";
print "Number of unique words : ", $count, "\n";
print "Most frequent word: ", "$tword $wct{$tword}" ,"\n";
print "\n";






