lorenzov has asked for the wisdom of the Perl Monks concerning the following question:
#solution 1, using regex and parsewords use Text::ParseWords; my $file = "zs_PS0001_9_epack_2006b.csv"; open(FILE,"<$file") or die("Could not open $file: $!."); $count = 0; # Process the data. while (<FILE>){ # Line used to debug the script taking only a few lines. exit if ($count >= 20); #print "=========================== Record $count\n"; $count++; print "myCounter: ", $count , "\n"; @words= $_ =~ m/"[^"\r\n]*"|[^,\r\n]*/mg; @result = "ewords(',', 0, @words ); #build the array for the database command #@myArray=($result[0],$result[2],$result[4],$result[6],$result[8],$res +ult[10],$result[12],$result[14],$result[16],$result[18]); my $courseID=$result[0]; my $sessionID=$result[1]; my $userID=$result[2]; my $PersonID=$result[3]; my $mydatetime=$result[4]; my $millisecond=$result[5]; my $loc=$result[6]; my $action=$result[7]; my $page=$result[8]; my $time=$result[9]; print STDOUT "result: ", $courseID,"\n"; print STDOUT "result: ", $sessionID,"\n"; print STDOUT "result: ", $userID,"\n"; print STDOUT "result: ", $PersonID,"\n"; print STDOUT "result: ", $mydatetime,"\n"; print STDOUT "result: ", $millisecond,"\n"; print STDOUT "result: ", $loc,"\n"; print STDOUT "result: ", $action,"\n"; print STDOUT "result: ", $page,"\n"; print STDOUT "result: ", $time,"\n"; print STDOUT "***********\n"; } # end solution 1_______________________
now, if I'm running any of these with my CSV files, this is what i get (example from the first loop):# solution 2, using text:csv_xs use Text::CSV_XS; my $csv = Text::CSV_XS->new(); $count=0; my $file = 'PS0002_9_2006b.txt'; if (defined $ARGV[0]) { $file = $ARGV[0]; } my $sum = 0; open(my $data, '<', $file) or die "Could not open '$file'\n"; while (my $line = <$data>) { chomp $line; exit if ($count >= 20); $count++; if ($csv->parse($line)) { my @columns = $csv->fields(); $sum += $columns[2]; } else { warn "Line could not be parsed: $line\n"; } } print "$sum\n"; # end solution 2_______________________
my $courseID=substr($result[0],1);
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: CSV nightmare
by ikegami (Patriarch) on Jun 03, 2008 at 01:03 UTC | |
by graff (Chancellor) on Jun 03, 2008 at 02:49 UTC | |
by ikegami (Patriarch) on Jun 03, 2008 at 03:18 UTC | |
|
Re: CSV nightmare
by snoopy (Curate) on Jun 03, 2008 at 01:36 UTC | |
by Tux (Canon) on Jun 03, 2008 at 08:50 UTC | |
by ikegami (Patriarch) on Jun 03, 2008 at 10:36 UTC | |
by Tux (Canon) on Jun 03, 2008 at 15:10 UTC | |
by ikegami (Patriarch) on Jun 03, 2008 at 19:26 UTC | |
by ikegami (Patriarch) on Jun 04, 2008 at 23:19 UTC | |
| |
|
Re: CSV nightmare
by dragonchild (Archbishop) on Jun 03, 2008 at 13:14 UTC | |
|
Re: CSV nightmare
by Tux (Canon) on Jun 04, 2008 at 19:03 UTC |