#!/usr/bin/perl
print "Hello, world!\n";  # a short Perl example

# modify to point to a particular version of perl
# on a UNIX system (like gl.umbc.edu) use the chmod command to make this 
# file execuatble, e.g. chmod +x PerlCheatSheet.pl
#
# then just run this file like any executable, e.g. ./PerlCheatSheet
# no .pl suffix is needed since the shell will find it

# let's make sure we can run this "program" using its own source as input!

# Perl statements end with a semicolon
# ordinary variables begin with $
$nDocs = 0;

# Perl has built-in hash functions
%aHashTable = ();  # will be used in example below

#control structures include while, for, and foreach

# simple echo of STDIN to STDOUT
while ($inputLine = <STDIN>) {
    chomp $inputLine;  # get rid of trailing newline
    print STDOUT "$inputLine\n";   #  I/O looks very C-like, eh?

    # array names begin with @ 
    # split $inputLine into an array of blank-separated words
    @words=split(" ", $inputLine); 
    foreach $word (@words) {
	$aHashTable{$word} += 1;
    }
}

# lots of string matching operators, including s for substitute
$aString = "Do not do that!";
print $aString
$aString =~ s/Do not/Don't/;
print $aString;

for $word (sort(keys(%aHashTable))) {
    $nTerms++;
    # but let's make each word lower-case
    $wordlc = $word;
    $wordlc =~ tr/A-Z/a-z/;  # tr stands for translate
    printf STDOUT "%s, %d\n", $wordlc, $aHashTable{$word};
}

# run an external command and save the output
# from Learning Perl by Brian d foy
@lines = `perldoc -u -f atan2`;

# let's make a spreadsheet
use Spreadsheet::WriteExcel;
# make some new objects
my $workbook = Spreadsheet::WriteExcel->new("lexicon.xls");
my $worksheet = $workbook->add_worksheet();
# write two column headers
$worksheet->write(0,0,"term");
$worksheet->write(0,1,"count");

# now write each term, and its count, on its own row
$row = 1;
for $word (sort(keys(%aHashTable))) {
    # put $word in quotes, so excel won't try to evaluate it
    $worksheet->write($row, 0, sprintf("\"%s\"", $word)); 
    $worksheet->write($row, 1, $aHashTable{$word}); 
    $row++;
}

