Tuesday, March 11, 2008

Regex Loves Jenny

The following script now works. Yay!

For the longest time -- at least 15 minutes -- I thought I was incapable of understanding regex because 2 lines of this script didn't work and the output was always blank:

$word =~ s/^\s+//;
$word =~ s/\s+$//;

But it turns out that the screen demons had changed the code:

$word =~ s/^\s+//;
$worn =~ s/\s+$//;

Since I never asked the computer to show me the contents of $worn, I never found out if they were in fact the right contents. It could have been an eldritch sigil in there -- we'll never know.

Also, I know this could have been accomplished without using a hash, but I wanted to practice. I'm wondering if there would have been a quicker way to get the blank spaces removed and the content into the hash though.

This is the script for posterity:
#!/usr/bin/perl

# open the file input by the user as PRICES
open(PRICES, $ARGV[0]);

#read in every line of PRICES
while (defined($line = <>))
{

# make sure @words array is empty
undef(@words);

# create array words and split the contents of the line into it at commas
@words = split(/,/, $line);

# If the values in the array contain blank spaces, remove them

foreach $word (@words)
{
# print("1: $word\n");
$word =~ s/^\s+//;
$word =~ s/\s+$//;
# print("2: $word\n");
}

# print((join("\n", @words) . "\n"));

# make sure pricetable hash is undefined
undef(%pricetable);

# add pricetable hash, assign array contents to hash
%pricetable = ("date" => "$words[0]",
"symbol" => "$words[1]",
"opening" => "$words[2]",
"closing" => "$words[3]",
"high" => "$words[4]",
"low" => "$words[5]",
"volume" => "$words[6]");

# calculate price change using absolute value

$change = abs($oldclose - $pricetable{closing});

# keep track of the current closing price for the next loop

$oldclose = $pricetable{closing};

# print exciting output

print("Date: " . "$pricetable{date}" . "," . " Price change: " . "$change" . "\n");


}

close(PRICES);

No comments: