File: CSV.pm

package info (click to toggle)
libtie-array-csv-perl 0.08-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 128 kB
  • sloc: perl: 302; makefile: 2
file content (469 lines) | stat: -rw-r--r-- 10,289 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
package Tie::Array::CSV;

use strict;
use warnings;

our $VERSION = '0.08';
$VERSION = eval $VERSION;

use Carp;

use Tie::File;
use Text::CSV;

use Scalar::Util qw/blessed/;

use Tie::Array;
our @ISA = ('Tie::Array');

sub parse_opts {
  my $class = shift;

  croak "Must specify a file" unless @_;

  my ($file, %opts);

  # handle one arg as either hashref (of opts) or file
  if (@_ == 1) {
    if (ref $_[0] eq 'HASH') {
      %opts = %{ shift() };
    } else {
      $file = shift;
    }
  }

  # handle file and hashref of opts
  if (@_ == 2 and ref $_[1] eq 'HASH') {
    $file = shift;
    %opts = %{ shift() };
  }

  # handle file before hash of opts
  if (@_ % 2) {
    $file = shift;
  }

  # handle hash of opts
  if (@_) {
    %opts = @_;
  }

  # handle file passed has hash(ref) value to 'file' key
  if (!$file and defined $opts{file}) {
    $file = delete $opts{file};
  }

  # file wasn't specified as lone arg or as a hash opt
  croak "Must specify a file" unless $file;

  # parse specific options
  if (exists $opts{sep_char}) {
    $opts{text_csv}{sep_char} = delete $opts{sep_char};
  }

  return ($file, \%opts);
}

sub new {
  my $class = shift;
  my ($file, $opts) = $class->parse_opts(@_);

  my @self;
  tie @self, $class, $file, $opts;

  return \@self;

}

sub TIEARRAY {
  my $class = shift;
  my ($file, $opts) = $class->parse_opts(@_);

  my @tiefile;
  tie @tiefile, 'Tie::File', $file, recsep => "\n", %{ $opts->{tie_file} || {} }
    or croak "Cannot tie file $file";

  my $csv;
  if (blessed $opts->{text_csv} and $opts->{text_csv}->isa('Text::CSV')) {
    $csv = $opts->{text_csv};
  } else {
    $csv = Text::CSV->new($opts->{text_csv} || {}) 
      or croak "CSV (new) error: " . Text::CSV->error_diag();
  }

  my $self = {
    file => \@tiefile,
    csv => $csv,
  };

  bless $self, $class;

  return $self;
}

sub FETCH {
  my $self = shift;
  my $index = shift;

  my $line = $self->{file}[$index];

  my $rowclass = ref($self) . '::Row';
  tie my @line, $rowclass, { 
    file => $self->{file},
    line_num => $index,
    fields => $self->_parse($line), 
    csv => $self->{csv},
  };

  return \@line;
}

sub STORE {
  my $self = shift;
  my ($index, $value) = @_;

  $self->{file}[$index] = $self->_combine($value);
}

sub FETCHSIZE {
  my $self = shift;

  return scalar @{ $self->{file} };
}

sub STORESIZE {
  my $self = shift;
  my $new_size = shift;

  $#{ $self->{file} } = $new_size - 1;
  
}

sub EXISTS { 
  my $self = shift;
  my ($index) = shift;
  return exists $self->{file}[$index];
}

sub DELETE { 
  my $self = shift;
  my $index = shift;
  return $self->SPLICE($index,1);
}

sub _parse {
  my $self = shift;
  my ($line) = @_;
  $line = '' unless defined $line;

  return [$self->{csv}->fields] if $self->{csv}->parse($line);

  croak "CSV parse error: " . $self->{csv}->error_diag;
}

sub _combine {
  my $self = shift;
  my ($value) = @_;

  return $self->{csv}->string
    if $self->{csv}->combine( ref $value ? @$value : ($value) );

  croak "CSV combine error: " . $self->{csv}->error_diag();
}

package Tie::Array::CSV::Row;

use Carp;

use Tie::Array;
our @ISA = ('Tie::Array');

use overload 
  '@{}' => sub{ $_[0]{fields} };

sub TIEARRAY {
  my $class = shift;
  my $self = shift;

  bless $self, $class;

  return $self;
}

sub FETCH {
  my $self = shift;
  my $index = shift;

  return $self->{fields}[$index];
}

sub STORE {
  my $self = shift;
  my ($index, $value) = @_;

  $self->{fields}[$index] = $value;

  $self->_update;

}

sub FETCHSIZE {
  my $self = shift;

  return scalar @{ $self->{fields} };
}

sub STORESIZE {
  my $self = shift;
  my $new_size = shift;

  my $return = (
    $#{ $self->{fields} } = $new_size - 1
  );

  $self->_update;

  return $return;
}

sub SHIFT {
  my $self = shift;

  my $value = shift @{ $self->{fields} };

  $self->_update;

  return $value;
}

sub UNSHIFT {
  my $self = shift;
  my $value = shift;

  unshift @{ $self->{fields} }, $value;

  $self->_update;

  return $self->FETCHSIZE();
}

sub DELETE {
  my $self = shift;
  my $index = shift;

  my $return = splice @{ $self->{fields} }, $index, 1;
  $self->_update;

  return $return;
}

sub EXISTS {
  my $self = shift;
  my $index = shift;

  return exists $self->{fields}[$index];
}

sub _update {
  my $self = shift;

  if(@{ $self->{fields} }) {
    $self->{csv}->combine(@{ $self->{fields} })
      or croak "CSV combine error: " . $self->{csv}->error_diag();
    $self->{file}[$self->{line_num}] = $self->{csv}->string;
  } else {
    $self->{file}[$self->{line_num}] = '';
  }
}

__END__
__POD__

=head1 NAME

Tie::Array::CSV - A tied array which combines the power of Tie::File and Text::CSV

=head1 SYNOPSIS

 use strict; use warnings;
 use Tie::Array::CSV;
 tie my @file, 'Tie::Array::CSV', 'filename';

 print $file[0][2];
 $file[3][5] = "Camel";

=head1 DESCRIPTION

This module allows an array to be tied to a CSV file for reading and writing. The array is a standard Perl 2D array (i.e. an array of array references) which gives access to the row and column of the user's choosing. This is done using the well established modules:

=over

=item * 
L<Tie::File>

=over

=item *

arbitrary line access

=item *

low memory use even for large files

=back

=item *

L<Text::CSV> 

=over

=item *

row parsing

=item *

row updating

=item *

uses the speedy L<Text::CSV_XS> if installed

=back

=back

This module was inspired by L<Tie::CSV_File> which (sadly) hasn't been maintained. It also doesn't attempt to do any of the parsing (as that module did), but rather passes all of the heavy lifting to other modules.

Note that while the L<Tie::File> prevents the need to read in the entire file, while in use, a parsed row IS held in memory.

=head1 CONSTRUCTORS

Since version 0.04 both constructors allow the options that version 0.03 only offered for the C<new> constructor. The constructors must be passed a file name, either as the first argument, or as the value to the option key C<file>. Options may be passed as key-value pairs or as a hash reference. This yields the many ways of calling the constructors shown below, one for every taste.

N.B. Should a lone argument filename and a C<file> option key both be passed to the constructor, the lone argument wins.

=head2 C<tie> Constructor

As with any tied array, the construction uses the C<tie> function. Basic usage is as follows:

 tie my @file, 'Tie::Array::CSV', 'filename';

which would tie the lexically scoped array C<@file> to the file C<filename> using this module. Following the first two arguements to C<tie>, one may optionally pass a key-value pairs or a hashref containing additional configuration or even file specification.

 tie my @file, 'Tie::Array::CSV', 'filename', { opt_key => val, ... };
 tie my @file, 'Tie::Array::CSV', 'filename', opt_key => val, ... ;
 tie my @file, 'Tie::Array::CSV', { file => 'filename', opt_key => val, ... };
 tie my @file, 'Tie::Array::CSV', file => 'filename', opt_key => val, ... ;

Of course, the magical Perl C<tie> can be scary for some, for those people there is the ...

=head2 C<new> Constructor

[ Added in version 0.03 ]

 my $array = Tie::Array::CSV->new( 'filename' );
 my $array = Tie::Array::CSV->new( 'filename', { opt_key => val, ... });
 my $array = Tie::Array::CSV->new( 'filename', opt_key => val, ... );
 my $array = Tie::Array::CSV->new( file => 'filename', opt_key => val, ... );
 my $array = Tie::Array::CSV->new( { file => 'filename', opt_key => val, ... } );

It only returns a reference to the C<tie>d array due to a limitations in how C<tie> magic works. 

=head2 Options

=over

=item *

C<file> - alternative method for specifing the file to C<tie>. This is overridden by a lone filename or handle passed as the first argument to the constructor.

=item *

C<tie_file> - hashref of options which are passed to the L<Tie::File> constructor

=item *

C<text_csv> - either:

=over

=item *

hashref of options which are passed to the L<Text::CSV> constructor

=item * 

an object which satisfies C<< isa('Text::CSV') >> (added in version 0.05)

=back

=item *

C<sep_char> - for ease of use, a C<sep_char> option may be specified, which is passed to the L<Text::CSV> constructor. This option overrides a corresponding entry in the C<text_csv> pass-through hash.

=back

Equivalent examples:

 tie my @file, 'Tie::Array::CSV', 'filename', { 
   tie_file => {}, 
   text_csv => { sep_char => ';' },
 };

 tie my @file, 'Tie::Array::CSV', 'filename', sep_char => ';';

Note that as of version 0.05 the functionality from the former C<hold_row> option has been separated into its own subclass module L<Tie::Array::CSV::HoldRow>. If deferring row operations is of interest to you, please see that module.

=head1 ERRORS

For simplicity this module C<croak>s on all almost all errors, which are trappable using a C<$SIG{__DIE__}> handler. Modifing a severed row object issues a warning.

=head1 CAVEATS

=over 

=item *

Much of the functionality of normal arrays is mimicked using L<Tie::Array>. The interaction of this with L<Tie::File> should be mentioned in that certain actions may be very inefficient. For example, C<(un)shift>-ing the first row of data will probably involve L<Tie::Array> asking L<Tie::File> to move each row up one line, one-by-one. As a note, the intra-row C<(un)shift> does not suffer this problem.

=item *

At one time, some effort was been made to allow for fields which contain linebreaks. Quickly it became clear that linebreaks would change line numbers used for row access by L<Tie::File>. Attempts to compensate for this, unfortunately, moved the module far from its stated goals, and therefore far less powerful for its intended purposes. The decision has been made (for now) not to support such files.

=back

=head1 SEE ALSO

=over

=item *

L<Tie::CSV_File> - inspiration for this module, but problematic

=back

=head1 SOURCE REPOSITORY

L<http://github.com/jberger/Tie-Array-CSV>

=head1 AUTHOR

Joel Berger, E<lt>joel.a.berger@gmail.comE<gt>

=head1 CONTRIBUTORS

Christian Walde (Mithaldu)
Graham Ollis (plicease)

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2013 by L</AUTHOR> and L</CONTRIBUTORS>.

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut