1 package BSE::Importer::Source::CSV;
3 use base 'BSE::Importer::Source::Base';
6 our $VERSION = "1.000";
8 my @text_csv_options = qw(quote_char escape_char sep_char binary allow_loose_quotes allow_loose_escapes allow_whitespace);
10 my @escape_options = qw(quote_char escape_char sep_char);
14 BSE::Importer::Source::CSV - import source for CSV files.
20 ; these are the defaults
33 Uses CSV (comma separated values) text files a data source.
37 The following extra configuration can be set in the profile's
38 configuration, (mostly better described in L<Text::CSV>.
44 C<skiplines> - the number of lines for skip at the top, eg. for column
49 C<binary> - whether the file should be treated as binary. The default
50 is typically correct. Default: 1.
54 C<sep_char> - the separator character between columns. Default: ",".
61 C<allow_whitespace> - set to true to ignore whitespace around the
62 separator. Default: 0.
66 C<encoding> - the character encoding to use in the input text.
71 C<quote_char> - the character used for quoting fields containing
72 blanks or separators. Default: '"'.
76 C<escape_char> - the character used for quote escapes. Default: '"'.
83 my ($class, %opts) = @_;
85 my $self = $class->SUPER::new(%opts);
87 my $importer = delete $opts{importer};
88 my $opts = delete $opts{opts};
90 $self->{skiplines} = $importer->cfg_entry('skiplines', 1);
92 $self->{encoding} = $importer->cfg_entry('encoding', 'utf-8');
93 my %csv_opts = ( binary => 1 );
94 for my $opt (@text_csv_options) {
95 my $val = $importer->cfg_entry($opt);
96 defined $val and $csv_opts{$opt} = $val;
99 for my $opt (@escape_options) {
100 if (defined (my $val = $csv_opts{$opt})) {
101 if ($val =~ /\A\\(?:[nrtfbae]|x[0-9a-fA-F]{2}|[0-7]{1,3}|c.)\z/) {
102 $csv_opts{$opt} = eval '"' . $val . '"';
107 $self->{csv_opts} = \%csv_opts;
113 my ($self, $importer, $filename) = @_;
115 open my $fh, "<encoding($self->{encoding})", $filename
116 or die "Cannot open file $filename: $!\n";
118 my $csv = Text::CSV->new($self->{csv_opts})
119 or die "Cannot use CSV: ", Text::CSV->error_diag(), "\n";
121 for my $line (1 .. $self->{skiplines}) {
122 my $row = $csv->getline($fh);
125 die "Ran out of rows reading the headers\n";
128 die "Error reading header rows: ", $csv->error_diag, "\n";
133 while (my $row = $csv->getline($fh)) {
136 $importer->row($self);
141 my ($self, $colnum) = @_;
143 $colnum > @{$self->{row}}
146 return $self->{row}[$colnum-1];
152 return "Line " . $self->{line};
159 Tony Cook <tony@develop-help.com>