Grid.pm

filter: Statementstmt 51.0% 48 / 94 Branchbran 0.0% 0 / 28 Conditioncond 0.0% 0 / 13 MC/DCmcdc 0.0% 0 / 7 Subroutinesub 52.6% 10 / 19 Podpod 100% 3 / 3 totaltotal 37.2% 61 / 164 CC 21 SCAR 49.3
CC
21
Cov
36%
parse
306.0
table_params
30.0
__ANON__
2.0
CRAP 137.8
↑ Summary Grid/CSV.pm »
1 package Data::Grid;
2  
3 1 ▶use 5.014;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use warnings FATAL => 'all';
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 1 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 # module-loading paraphernalia
10 1 ▶use String::RewritePrefix ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use Class::Load ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 1 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 1 ▶use Data::Grid::Types qw(FHlike Source Fields HeaderFlags Offsets
Subroutine BEGIN: called CC=1 SCAR=0.0
15 1 Checker to_Checker);
16 1 ▶use Type::Params qw(compile multisig Invocant);
Subroutine BEGIN: called CC=1 SCAR=0.0
17 1 ▶use Types::Standard qw(slurpy Optional ClassName Any Bool
Subroutine BEGIN: called CC=1 SCAR=0.0
18 1 Str ScalarRef HashRef Enum Dict);
19  
20 #use overload '@{}' => 'tables';
21  
22 # store it this way then flip it around
23  
24 1 my %MAP = (
25 CSV => [qw(text/plain text/csv text/tab-separated-values)],
26 Excel => [qw(application/x-ole-storage application/vnd.ms-excel
27 application/msword application/excel)],
28 'Excel::XLSX' => [
29 qw(application/x-zip application/x-zip-compressed application/zip
30 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)],
31 );
32 1 %MAP = map { my $k = $_; my @x = @{$MAP{$k}}; map { $_ => $k } @x } keys %MAP;
33  
34 =head1 NAME
35  
36 Data::Grid - Incremental read access to grid-based data
37  
38 =head1 VERSION
39  
40 Version 0.07
41  
42 =cut
43  
44 1 our $VERSION = '0.07';
45  
46 =head1 SYNOPSIS
47  
48 use Data::Grid;
49  
50 # Have the parser guess the kind of file, using defaults.
51  
52 my $grid = Data::Grid->parse('arbitrary.xls');
53  
54 # or
55  
56 my $grid = Data::Grid->parse(
57 source => 'arbitrary.csv', # or xls, or xlsx, or filehandle...
58 header => 1, # first line is a header everywhere
59 columns => [qw(a b c)], # override the header
60 options => \%options, # driver-specific options
61 );
62  
63 # Each object contains one or more tables.
64  
65 for my $table ($grid->tables) {
66  
67 # Each table has one or more rows.
68  
69 while (my $row = $table->next) {
70  
71 # The columns can be dereferenced as an array,
72  
73 my @cols = @$row; # or just $row->columns
74  
75 # or, if header is present or fields were named in the
76 # constructor, as a hash.
77  
78 my %cols = %$row;
79  
80 # Now we can do stuff.
81 }
82 }
83  
84 =head1 DESCRIPTION
85  
86 =over 4
87  
88 =item Problem 1
89  
90 You have a mountain of data files from two decades of using MS Office
91 (and other) products, and you want to collate their contents into
92 someplace sane.
93  
94 =item Problem 2
95  
96 The files are in numerous different formats, and a consistent
97 interface would really cut down on the effort of extracting them.
98  
99 =item Problem 3
100  
101 You've looked at L<Data::Table> and L<Spreadsheet::Read>, but deemed
102 their table-at-a-time strategy to be inappropriate for your purposes.
103  
104 =back
105  
106 The goal of L<Data::Grid> is to provide an extensible, uniform,
107 object-oriented interface to all kinds of grid-shaped data. A key
108 behaviour I'm after is to perform an incremental read over a
109 potentially large data source, so as not to unnecessarily gobble up
110 system resources.
111  
112 =head1 DEVELOPER RELEASE
113  
114 Odds are I will probably decide to change the interface at some point
115 before locking in, and I don't want to guarantee consistency yet. If I
116 do, and you use this, your code will probably break.
117  
118 Suffice to say this module is B<ALPHA QUALITY> at best.
119  
120 =head1 METHODS
121  
122 =head2 parse $FILE | %PARAMS
123  
124 The principal way to instantiate a L<Data::Grid> object is through the
125 C<parse> factory method. You can either pass it a filelike thing or a
126 set of parameters. I<Filelike thing> is either a filename, C<GLOB>
127 reference, C<SCALAR> reference or C<ARRAY> reference of scalars. If
128 the filelike thing is passed alone, its type will be detected using
129 L<File::MMagic>. To tune this behaviour, use the parameters:
130  
131 =over 4
132  
133 =item source
134  
135 This is equivalent to C<$file>.
136  
137 =item header
138  
139 If you know that the document you're opening has a header, set this
140 flag to a true value and it will be consumed for use in
141 L<Data::Grid::Row/as_hash>. If there is more than one table in the
142 document, set this value to an C<ARRAY> reference of flags. This
143 object will be treated as a ring, meaning that, for instance, if the
144 header designation is C<[1, 0]>, the third table in the document will
145 be treated as having a header, fourth will not, the fifth will, and so
146 on.
147  
148 =cut
149  
150 0 ▶my $zero_aref = sub { [0] };
Subroutine __ANON__: not called CC=1 SCAR=1.2
151  
152 1 has header => (
153 is => 'ro',
154 isa => HeaderFlags,
155 coerce => 1,
156 default => $zero_aref,
157 );
158  
159 =item columns
160  
161 Specify a list of columns in lieu of a header, or otherwise override
162 any header, which is thrown away. A single C<ARRAY> reference of
163 strings will be duplicated to each table in the document. An array of
164 arrays will be applied to each table with the same wrapping behaviour
165 as C<header>.
166  
167 =cut
168  
169 has columns => (
170 is => 'ro',
171 isa => Fields,
172 coerce => 1,
173 0 ▶ default => sub { [] },
Subroutine __ANON__: not called CC=1 SCAR=6.9
174 1 );
175  
176 =item start
177  
178 Set a row offset, i.e, a number of rows to skip I<before> any header.
179 Since this is an offset, it starts with zero. Same rule applies for
180 multiple tables in the document.
181  
182 =cut
183  
184 1 has start => (
185 is => 'ro',
186 isa => Offsets,
187 coerce => 1,
188 default => $zero_aref,
189 );
190  
191 =item skip
192  
193 Set a number of rows to skip I<after> the header, defaulting, of
194 course, to zero. Same multi-table rule applies.
195  
196 =cut
197  
198 1 has skip => (
199 is => 'ro',
200 isa => Offsets,
201 coerce => 1,
202 default => $zero_aref,
203 );
204  
205 =item options
206  
207 This C<HASH> reference will be passed as-is to the driver.
208  
209 =item driver
210  
211 Specify a driver and bypass type detection. Modules under the
212 L<Data::Grid> namespace can be handed in as L<CSV|Data::Grid::CSV>,
213 L<Excel|Data::Grid::Excel>, and L<Excel::XLSX|Data::Grid::Excel::XLSX>.
214 Prefix with a C<+> for other package namespaces.
215  
216 =item checker
217  
218 Specify either L<MMagic|File::MMagic> or L<MimeInfo|File::MimeInfo> to
219 detect the type of file. L<MMagic|File::MMagic> is the default. In
220 lieu of the class name
221  
222 =back
223  
224 =cut
225  
226  
227 my %CHECK = (
228 'File::MMagic' => [
229 # filename-based
230 0 ▶ sub { $_[0]->checktype_filename($_[1]) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
231 # fh-based
232 0 ▶ sub { $_[0]->checktype_filehandle($_[1]) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
233 ],
234 'File::MimeInfo::Magic' => [
235 # filename-based
236 0 ▶ sub { $_[0]->mimetype($_[1]) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
237 # fh-based
238 0 ▶ sub { $_[0]->mimetype($_[1]) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
239 1 ],
240 );
241  
242 0 ▶sub parse {
Subroutine parse: not called CC=17 SCAR=57.2
Pod documented
243 0 state $check = Type::Params::multisig(
244 [Invocant, Source],
245 [Invocant, slurpy Dict[source => Source,
246 header => Optional[HeaderFlags],
247 columns => Optional[Fields],
248 options => Optional[HashRef],
249 driver => Optional[ClassName],
250 checker => Optional[Checker],
251 slurpy Any]]
252 );
253  
254 0 my ($class, $p) = $check->(@_);
255 0 ▶ my %p = ref $p eq 'HASH' ? %$p : (source => $p);
Branch: 1 branch
BranchTrueFalseTotal
ref $p eq 'HASH' ? : 0 0 0
256  
257 # croak unless source is defined
258 Carp::croak("I can't do any work unless you specify a data source.")
259 0 ▶ unless defined $p{source};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $p{"source"} 0 0 0
260  
261 0 my $ref = ref $p{source};
262  
263  
264 #require Data::Dumper;
265 #warn Data::Dumper::Dumper(\%p);
266  
267 0 ▶ if ($ref) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ref) { } 0 0 0
268 # if it is a reference, it depends on the kind
269 0 ▶ if ($ref eq 'SCALAR') {
Branch: 3 branches
BranchTrueFalseTotal
if ($ref eq 'SCALAR') { } 0 0 0
elsif ($ref eq 'ARRAY') { } 0 0 0
elsif ($ref eq 'GLOB' or builtin::blessed($p{'source'}) and $p{'source'}->isa('IO::Seekable')) { } 0 0 0
270 # scalar ref as a literal
271 0 require IO::Scalar;
272 0 $p{fh} = IO::Scalar->new($p{source});
273 }
274 elsif ($ref eq 'ARRAY') {
275 # array ref as a list of lines
276 0 require IO::ScalarArray;
277 0 $p{fh} = IO::ScalarArray->new($p{source});
278 }
279 ▶ elsif ($ref eq 'GLOB' or Scalar::Util::blessed($p{source})
Condition0%0/6
$ref eq "GLOB" or builtin::blessed($p{"source"}) and $p{"source"}->isa("IO::Seekable")
l!l&&r!l&&!r
000
builtin::blessed($p{"source"}) and $p{"source"}->isa("IO::Seekable")
!ll&&!rl&&r
000
MC/DC0%0/3
$ref eq "GLOB" or builtin::blessed($p{"source"}) and $p{"source"}->isa("IO::Seekable")
$ref eq "GLOB" builtin::blessed($p{"source"}) $p{"source"}->isa("IO::Seekable")
Truth table0%0/4
A or B and C
A= $ref eq "GLOB"B= builtin::blessed($p{"source"})C= $p{"source"}->isa("IO::Seekable")
ABCresult
1XX1
0111
00X0
0100
280 && $p{source}->isa('IO::Seekable')) {
281 # ioref as just a straight fh
282 0 $p{fh} = $p{source};
283 }
284 else {
285 # dunno
286 0 Carp::croak("Don't know what to do with $ref as a source.");
287 }
288 }
289 else {
290 # if it is a string, it is assumed to be a filename
291 0 require IO::File;
292 0 ▶ $p{fh} = IO::File->new($p{source}) or Carp::croak($!);
Branch: 1 branch
BranchTrueFalseTotal
$p{"fh"} = "IO::File"->new($p{"source"}) or Carp::croak($!) 0 0 0
293 }
294  
295 # binary this because it gets messed up otherwise
296 0 binmode $p{fh};
297  
298 # if you didn't specify a driver we pick one for you
299 0 ▶ unless ($p{driver}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($p{"driver"}) 0 0 0
300 0 ▶ my $checker ||= to_Checker('MMagic');
Condition0%0/3
my $checker ||= &to_Checker("MMagic")
l!l&&r!l&&!r
000
MC/DC0%0/2
my $checker ||= &to_Checker("MMagic")
my $checker &to_Checker("MMagic")
Truth table0%0/3
A ||= B
A= my $checkerB= &to_Checker("MMagic")
ABresult
1X1
011
000
301 0 my ($ckey) = grep { $checker->isa($_) } sort keys %CHECK;
302  
303 0 my $type;
304 0 ▶ unless ($ref) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ref) 0 0 0
305 # check the type by filename
306 0 ▶ $type = $CHECK{$ckey}[0]->($checker, $p{source}) // '';
Condition0%0/2
$CHECK{$ckey}[0]->($checker, $p{"source"}) // ""
l!l
00
MC/DC0%0/1
$CHECK{$ckey}[0]->($checker, $p{"source"}) // ""
$CHECK{$ckey}[0]->($checker, $p{"source"})
Truth table0%0/2
A
A= $CHECK{$ckey}[0]->($checker, $p{"source"})
Aresult
11
00
307 # do not continue unless we get a match
308 0 ▶ undef $type unless $MAP{$type};
Branch: 1 branch
BranchTrueFalseTotal
unless $MAP{$type} 0 0 0
309 }
310  
311 # now check the filehandle
312 0 ▶ unless ($type) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($type) 0 0 0
313 0 $type = $CHECK{$ckey}[1]->($checker, $p{fh});
314 # reset the filehandle
315 0 seek $p{fh}, 0, 0;
316 }
317  
318 Carp::croak("There is no driver mapped to the detected type $type")
319 0 ▶ unless $MAP{$type};
Branch: 1 branch
BranchTrueFalseTotal
unless $MAP{$type} 0 0 0
320  
321 0 $p{driver} = $MAP{$type};
322 }
323  
324 # now load the driver
325 (my $driver) = String::RewritePrefix->rewrite
326 0 ({ '' => 'Data::Grid::', '+' => ''}, delete $p{driver});
327 0 Class::Load::load_class($driver);
328  
329 0 $driver->new(%p);
330 }
331  
332 =head2 tables
333  
334 Generate and return the array of tables.
335  
336 =cut
337  
338 0 ▶sub tables {
Subroutine tables: not called CC=1 SCAR=6.9
Pod documented
339 0 Carp::croak('This is a stub method that must be overridden.');
340 }
341  
342 =head2 fh
343  
344 Retrieve the document's file handle embedded in the grid object.
345  
346 =cut
347  
348 1 has fh => (
349 is => 'ro',
350 isa => FHlike,
351 required => 1,
352 init_arg => 'fh',
353 );
354  
355 =head1 EXTENSION INTERFACE
356  
357 Take a look at L<Data::Grid::CSV> or L<Data::Grid::Excel> for clues on
358 how to extend this package.
359  
360 =head2 table_class
361  
362 Returns the class to use for instantiating tables. Defaults to
363 L<Data::Grid::Table>, which is an abstract class. Override this
364 accessor and its neighbours with your own values for extensions.
365  
366 =cut
367  
368 1 has table_class => (
369 is => 'ro',
370 isa => ClassName,
371 default => 'Data::Grid::Table',
372 );
373  
374 =head2 row_class
375  
376 Returns the class to use for instantiating rows. Defaults to
377 L<Data::Grid::Row>.
378  
379 =cut
380  
381 1 has row_class => (
382 is => 'ro',
383 isa => ClassName,
384 default => 'Data::Grid::Row',
385 );
386  
387 =head2 cell_class
388  
389 Returns the class to use for instantiating cells. Defaults to
390 L<Data::Grid::Cell>, again an abstract class.
391  
392 =cut
393  
394 1 has cell_class => (
395 is => 'ro',
396 isa => ClassName,
397 default => 'Data::Grid::Cell',
398 );
399  
400 =head2 table_params $POSITION
401  
402 Generate a set of parameters suitable for passing in as a constructor,
403 either as a hash or C<HASH> reference, depending on calling context.
404  
405 =cut
406  
407 0 ▶sub table_params {
Subroutine table_params: not called CC=5 SCAR=34.0
Pod documented
408 0 my ($self, $pos) = @_;
409  
410 0 my %p = (parent => $self, position => $pos);
411  
412 # okay this goes through all similar arrayref members and picks
413 # the element that corresponds to the table modulo the length of
414 # the list of tables, which frankly is pretty clever
415 0 for my $k (qw(header columns start skip)) {
416 0 ▶ my @x = @{$self->$k || []};
Condition0%0/2
$self->$k || []
l!l
00
MC/DC0%0/1
$self->$k || []
$self->$k
Truth table0%0/2
A
A= $self->$k
Aresult
11
00
417 0 ▶ $p{$k} = $x[$pos % @x] if @x;
Branch: 1 branch
BranchTrueFalseTotal
if @x 0 0 0
418 }
419  
420 0 ▶ wantarray ? %p : \%p;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
421 }
422  
423 =head1 AUTHOR
424  
425 Dorian Taylor, C<< <dorian at cpan.org> >>
426  
427 =head1 BUGS
428  
429 Please report bugs to L<GitHub
430 issues|https://github.com/doriantaylor/p5-data-grid/issues>.
431  
432 =head1 SUPPORT
433  
434 You can find documentation for this module with the perldoc command.
435  
436 perldoc Data::Grid
437  
438 Alternatively, you can read the documentation on
439 L<MetaCPAN|https://metacpan.org/release/Data::Grid>.
440  
441 =head1 SEE ALSO
442  
443 =over 4
444  
445 =item
446  
447 L<Text::CSV>
448  
449 =item
450  
451 L<Spreadsheet::ParseExcel>
452  
453 =item
454  
455 L<Spreadsheet::ParseXLSX>
456  
457 =item
458  
459 L<Data::Table>
460  
461 =back
462  
463 =head1 COPYRIGHT & LICENSE
464  
465 Copyright 2010-2018 Dorian Taylor.
466  
467 Licensed under the Apache License, Version 2.0 (the "License"); you
468 may not use this file except in compliance with the License. You may
469 obtain a copy of the License at
470 L<http://www.apache.org/licenses/LICENSE-2.0>.
471  
472 Unless required by applicable law or agreed to in writing, software
473 distributed under the License is distributed on an "AS IS" BASIS,
474 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
475 implied. See the License for the specific language governing
476 permissions and limitations under the License.
477  
478 =cut
479  
480 1 1; # End of Data::Grid
↑ Summary Grid/CSV.pm »