Parse A CSV String Using Perl
Parsing a CSV file with perl is probably one of the simpler thing’s you’ll have to do in life. You could use something as simple as
my @line = split(/,/,$somedata);
Or even simpler, you could use the Perl Package Text::CSV, which I would recommend because if you are like me you parse financial data alot! So When a company like Goldman Sachs Group, Inc. shows up…the “,” before the Inc can throw you off. However Text::CSV is smart enough to know that if the value is in quotes….not to split it.
Well the problem I ran into the other day was I was trying to login to Google Finance using perl, which was also surprisingly easy to do. I wanted just the names in my portfolio so I could use them to query other data not available the way I’d like to see it in Google. (To be more specific, I wanted a report that showed all my Dividend paying stocks. Their EX-Dates and Pay dates all in one page. )
Well Google has been nice enough to allow me to download my Portfolio in CSV format. Nice! The one problem is that when you go to the link with WWW::Mechanize, the content is returned as a string. Not a line by line file, like I am used to.
So the very, very simple solution was to split the string on New lines and store them in an Array. Then loop through each line, and use Text::CSV to give me the fields. Since I only wanted the symbol field, I only print it.
Here is the code snippet:
our $csv = Text::CSV->new();
my @line = split(/\n/,$output_page);
foreach (@line) {
my $data = $csv->parse($_);
my @fields = $csv->fields();
print “$fields[1]\n”;
}

Leave a Reply