I am new to perl so please accept my apologies if my question is trivial. I have a very large file with data that looks like the following:
Date, Time, Data1, Data2, Data3
1/4/1999,9:31:00 AM,blah, blah, blah
1/4/1999,9:32:00 AM,blah, blah, blah
1/4/1999,9:33:00 AM,blah, blah, blah
I have a file named 'cities.txt' which has a list of cities located on different rows with a comma at the end of the row.
i.e.
Boston,
Atlanta,
Seattle,
Each city has its own file in that same directory that has the following naming convention 'Boston 1 Minute Moisture Data.txt'. I want to first read the 'cities.txt' file and for each city that appears in that file find the associated moisture data file and extract all the data (rows) between and including TWO sets of dates (a START and an END date) and SAVE that to another file. The date is located in the first column.
I have read through comments made in the following post but I am still very confused.
How do I efficiently parse a CSV file in Perl?
I wrote a simple script using some examples online. Firstly, I just wanted to see if I was using the module correctly. So all I wanted to do was to get the parser to parse the fields and calculate the sum of a specific column.
#!/usr/bin/perl
use strict;
use warnings;
use Text::CSV_XS;
my $csv = Text::CSV_XS->new();
my $file = 'Boston 1 Minute Moisture Data.csv';
my $sum = 0;
open(my $data, '<', $file) or die "Could not open '$file'\n";
while (my $line = <$data>) {
chomp $line;
if ($csv->parse($line)) {
my @columns = $csv->fields();
$sum += $columns[3];
} else {
warn "Line could not be parsed: $line\n";
}
}
print "$sum\n";
The result is get is "Line could not be parsed: $line\n". For some reason the parser isn't parsing the fields. Any ideas?
I also tried the following code:
#!/usr/bin/perl
use strict;
use warnings;
use Text::CSV;
my $file = 'Boston 1 Minute Moisture Data.csv';
my $csv = Text::CSV->new();
open (CSV, "<", $file) or die $!;
while (<CSV>) {
if ($csv->parse($_)) {
my @columns = $csv->fields();
#print "@columns\n";
print fields[1];
} else {
my $err = $csv->error_input;
print "Failed to parse line: $err";
}
}
close CSV;
I get the following result for every line in the file:
print() on unopened filehandle fields at test2.pl line 16, line 9326.