Created
May 10, 2016 11:14
-
-
Save fglock/0c91002af68a7ba074886edc196eea20 to your computer and use it in GitHub Desktop.
tweaked csv test to avoid "Exporter"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use strict; | |
use warnings; | |
#use Text::CSV::Easy_PP qw(csv_parse); | |
{ | |
package Text::CSV::Easy_PP; | |
use 5.010; | |
use strict; | |
use warnings FATAL => 'all'; | |
use Carp; | |
# use Exporter qw(import); | |
our @EXPORT_OK = qw(csv_build csv_parse); | |
sub csv_build { | |
my @fields = @_; | |
return join ',', map { | |
if ( !defined ) | |
{ | |
''; | |
} | |
elsif (/^\d+$/) { | |
$_; | |
} | |
else { | |
( my $str = $_ ) =~ s/"/""/g; | |
qq{"$str"}; | |
} | |
} @fields; | |
} | |
sub csv_parse { | |
my ($str) = @_; | |
return () unless $str; | |
my $last_pos = 0; | |
my @fields; | |
while ( | |
$str =~ / (?:^|,) | |
(?: "" # don't want a capture group here | |
| "(.*?)(?<![^"]")" # find quote which isn't being escaped | |
| ([^",\r\n]*) # try to match an unquoted field | |
) | |
(?:\r?\n(?=$)|) # allow a trailing newline only | |
(?=,|$) /xsg | |
) | |
{ | |
my $field = $1 || $2; | |
# is the field a numeric 0. | |
if ( defined($field) && $field =~ /^0+$/ ) { | |
# don't do anything. | |
} | |
else { | |
# if we don't have a value, we have either an undef or an empty string. | |
# "" will be an empty string, otherwise it should be undef. | |
$field ||= ( $& =~ /^,?""(?:\r?\n)?$/ ? "" : undef ); | |
} | |
# track the pos($str) to ensure each field happends immediately after the | |
# previous match. also, account for a leading comma when $last_pos != 0 | |
croak("invalid line: $str") | |
if pos($str) > $last_pos + length($&) + ( $last_pos != 0 ? 1 : 0 ); | |
$last_pos = pos($str); | |
if ($field) { | |
croak("quote is not properly escaped") | |
if ( $field =~ /(?<!")"(?!")/ ); | |
# unescape the quotes. | |
$field =~ s/""/"/g; | |
} | |
push @fields, $field; | |
} | |
croak("invalid line: $str") if $last_pos != length($str); | |
return @fields; | |
} | |
1; | |
} | |
my $sum = 0; | |
while (my $line = <>) { | |
my @row = Text::CSV::Easy_PP::csv_parse ($line); | |
$sum += @row; | |
} | |
print "$sum\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment