1 |
package WebPAC::Input::CSV; |
2 |
|
3 |
use warnings; |
4 |
use strict; |
5 |
|
6 |
use WebPAC::Input; |
7 |
use base qw/WebPAC::Common/; |
8 |
|
9 |
use Text::CSV; |
10 |
use Data::Dump qw/dump/; |
11 |
|
12 |
=head1 NAME |
13 |
|
14 |
WebPAC::Input::CSV - support for CSV Export Format |
15 |
|
16 |
=cut |
17 |
|
18 |
our $VERSION = '0.01'; |
19 |
|
20 |
=head1 FUNCTIONS |
21 |
|
22 |
=head2 new |
23 |
|
24 |
Returns new low-level input API object |
25 |
|
26 |
my $input = new WebPAC::Input::CSV( |
27 |
path => '/path/to/records.csv', |
28 |
); |
29 |
|
30 |
Options: |
31 |
|
32 |
=over 4 |
33 |
|
34 |
=item path |
35 |
|
36 |
path to CSV file |
37 |
|
38 |
=back |
39 |
|
40 |
Default encoding of input file is C<utf-8> |
41 |
|
42 |
=cut |
43 |
|
44 |
sub new { |
45 |
my $class = shift; |
46 |
my $self = {@_}; |
47 |
bless($self, $class); |
48 |
|
49 |
my $arg = {@_}; |
50 |
|
51 |
my $log = $self->_get_logger(); |
52 |
|
53 |
open( my $fh, '<:encoding(utf-8)', $arg->{path} ) || $log->logconfess("can't open $arg->{path}: $!"); |
54 |
|
55 |
my $csv = Text::CSV->new({ binary => 1 }); |
56 |
|
57 |
$self->{size} = 0; |
58 |
|
59 |
while ( 1 ) { |
60 |
my $line = $csv->getline( $fh ); |
61 |
last if $csv->eof; |
62 |
|
63 |
$log->logdie( "can't parse CSV file ", $csv->error_diag ) unless $line; |
64 |
|
65 |
my $rec; |
66 |
$rec->{'000'} = [ ++$self->{size} ]; |
67 |
|
68 |
my $col = 'A'; |
69 |
$rec->{ $col++ } = $_ foreach @$line; |
70 |
|
71 |
push @{ $self->{_rec} }, $rec; |
72 |
|
73 |
}; |
74 |
|
75 |
$log->debug("loaded ", $self->size, " records"); |
76 |
|
77 |
$self ? return $self : return undef; |
78 |
} |
79 |
|
80 |
=head2 fetch_rec |
81 |
|
82 |
Return record with ID C<$mfn> from database |
83 |
|
84 |
my $rec = $input->fetch_rec( $mfn, $filter_coderef ); |
85 |
|
86 |
=cut |
87 |
|
88 |
sub fetch_rec { |
89 |
my $self = shift; |
90 |
|
91 |
my ( $mfn, $filter_coderef ) = @_; |
92 |
|
93 |
return $self->{_rec}->[$mfn-1]; |
94 |
} |
95 |
|
96 |
|
97 |
=head2 size |
98 |
|
99 |
Return number of records in database |
100 |
|
101 |
my $size = $input->size; |
102 |
|
103 |
=cut |
104 |
|
105 |
sub size { |
106 |
my $self = shift; |
107 |
return $self->{size}; |
108 |
} |
109 |
|
110 |
=head1 AUTHOR |
111 |
|
112 |
Dobrica Pavlinusic, C<< <dpavlin@rot13.org> >> |
113 |
|
114 |
=head1 COPYRIGHT & LICENSE |
115 |
|
116 |
Copyright 2009 Dobrica Pavlinusic, All Rights Reserved. |
117 |
|
118 |
This program is free software; you can redistribute it and/or modify it |
119 |
under the same terms as Perl itself. |
120 |
|
121 |
=cut |
122 |
|
123 |
1; # End of WebPAC::Input::CSV |