added header_first to WebPAC::Input::CSV
[webpac2] / lib / WebPAC / Input / CSV.pm
index 26dab49..9f10579 100644 (file)
@@ -26,6 +26,7 @@ Returns new low-level input API object
 
   my $input = new WebPAC::Input::CSV(
        path => '/path/to/records.csv',
+       header_first => 1,
   );
 
 Options:
@@ -40,6 +41,8 @@ path to CSV file
 
 Default encoding of input file is C<utf-8>
 
+C<header_first> will use first line as header names.
+
 =cut
 
 sub new {
@@ -57,6 +60,12 @@ sub new {
 
        $self->{size} = 0;
 
+       if ( $self->{header_first} ) {
+               my $line = $csv->getline( $fh );
+               $self->{header_names} = $line;
+               $self->debug( "header_names = ",dump( $self->{header_names} ) );
+       }
+
        while ( 1 ) {
                my $line = $csv->getline( $fh );
                last if $csv->eof;
@@ -67,6 +76,8 @@ sub new {
                $rec->{'000'} = [ ++$self->{size} ];
 
                my $col = 'A';
+               my $header_pos = 0;
+
                foreach my $cell ( @$line ) {
                        my $str = eval { Encode::decode_utf8( $cell ) };
                        if ( $@ ) {
@@ -81,6 +92,11 @@ sub new {
                        }
                                
                        $rec->{ $col++ } = $str;
+
+                       if ( $self->{header_names} ) {
+                               $rec->{ $self->{header_names}->[$header_pos] } = $str;
+                               $header_pos++;
+                       }
                }
 
                push @{ $self->{_rec} }, $rec;