blib/lib/IO/Simple.pm

filter: Statementstmt 64.6% 73 / 113 Branchbran 33.3% 20 / 60 Conditioncond 30.7% 4 / 13 MC/DCmcdc 14.2% 1 / 7 Subroutinesub 46.6% 14 / 30 Podpod 52.1% 12 / 23 totaltotal 50.4% 124 / 246 CC 36 SCAR 20.9
CC
36
Cov
52%
set_option
30.0
reopen
12.0
_protect
12.0
CRAP 8.0
↑ Summary
1 package IO::Simple;
2
3 1 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6
7 1 require Exporter;
8 1 require IO::File;
9
10 1 our @ISA = qw(Exporter IO::File);
11
12 1 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 1 our %EXPORT_TAGS = ( 'all' => [ qw(
14 file slurp
15 ) ] );
16
17 1 our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
18
19 1 our @EXPORT = qw(
20 );
21
22 1 our $VERSION = '0.04';
23
24 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
25
26 =head1 NAME
27
28 IO::Simple - Adds error checking to file handles and provides per file handle options.
29
30 =head1 SYNOPSIS
31
32 You can export the C<file> method as below
33
34 use IO::Simple ':all';
35
36 my $fh = file('test.txt', 'w'); #dies if file can't be opened
37 $fh->say("This is a line"); #say appends new line
38 $fh->print("This has no new line!!!"); #regular print behavior
39 $fh->close(); #dies on failure
40
41 my $contents = file('test.txt')->slurp();
42
43 Or you can use the C<new> class method
44
45 use IO::Simple;
46 my $fh = new IO::Simple('test.txt');
47
48 =head1 DESCRIPTION
49
50 IO::Simple provides a thin layer over IO::File. This layer causes files to
51 default to opening in read mode and to croaking on failure opening, closeing
52 or printing to files. It provides methods to set $\, $/, $:, $^L and $, on a
53 per handle basis and a slurp function.
54
55 =head1 REASONING
56
57 You can get similar results using a combination of IO::All, Fatal and
58 File::Slurp. I found that fatal didn't provide as descriptive as errors as I
59 wanted, and IO::All was overly bloated so this module was born to fill in
60 those gaps.
61
62 =head1 METHODS
63
64 =over 4
65
66 =cut
67
68 1 my $data = {};
69 0 ▶sub data { $data };
Subroutine data: not called CC=1 SCAR=6.9
Pod undocumented
70
71 # internal method for inside out object operation
72 13 ▶sub id {
Subroutine id: called CC=1 SCAR=0.0
Pod undocumented
73 13 my $self = shift;
74 13 return 0+$self;
75 }
76
77 =item new IO::Simple ( [FILENAME [,MODE, [OPTIONS]]])
78
79 Passes any arguments to C<< $self->open >> for processing, otherwise simply
80 returns a new object.
81
82 =cut
83
84 3 ▶sub new {
Subroutine new: called CC=4 SCAR=15.0
Pod documented
85 3 my $type = shift;
86 3 ▶ my $class = ref($type) || $type || "IO::Simple";
Condition40%2/5
ref $type || $type || 'IO::Simple'
l!l
30
ref $type or $type
l!l&&r!l&&!r
030
MC/DC0%0/2
ref $type || $type || 'IO::Simple'
ref $type $type
Truth table33%1/3
A or B
A= ref $typeB= $type
ABresult
1X1
011
000
87 3 my $self = $class->SUPER::new();
88
89 3 $data->{id($self)} = {
90 file_name => '',
91 mode => '',
92 autochomp => 1
93 };
94
95 3 ▶ $self->open(@_) if (@_);
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 3 3
96 3 return $self;
97 }
98
99 =item $fh->open ( FILENAME [,MODE, [OPTIONS]])
100
101 C<file> accepts up to three parameters. If only FILENAME is supplied then
102 the default mode is 'read' The mode can be one of 'r',' 'read', 'w', 'write',
103 'a', 'append' which translate to '<', '>', and '>>'. The third parameter is
104 a hash of options. It also adds some magic so that the '-' file name will
105 cause STDIN or STDOUT to be opened depending on the mode.
106
107 Option Sets
108 line_break_characters $:
109 format_formfeed $^L
110 output_field_separator $,
111 output_record_separator $\
112 input_record_separator $/
113 autochomp auto chomp on readline or slurp
114
115 =cut
116
117 3 ▶sub open {
Subroutine open: called CC=7 SCAR=24.0
Pod documented
118 3 my $self = shift;
119 3 my $file_name = shift;
120 3 ▶ my $mode = shift || 'r';
Condition100%2/2
shift() || 'r'
l!l
21
MC/DC100%1/1
shift() || 'r'
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
121 3 ▶ if ($file_name eq '-') {
Branch: 1 branch
BranchTrueFalseTotal
if ($file_name eq '-') { } 0 3 3
122 0 ▶ if ($mode =~ /r|</) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mode =~ /r|</) { } 0 0 0
123 0 ▶ $self->fdopen('STDIN', $mode) or croak "Opening '$file_name' for '$mode' failed: $!";
Branch: 1 branch
BranchTrueFalseTotal
$self->fdopen("STDIN", $mode) or croak("Opening '${file_name}' for '${mode}' failed: $!") 0 0 0
124 } else {
125 0 ▶ $self->fdopen('STDOUT', $mode) or croak "Opening '$file_name' for '$mode' failed: $!";
Branch: 1 branch
BranchTrueFalseTotal
$self->fdopen("STDOUT", $mode) or croak("Opening '${file_name}' for '${mode}' failed: $!") 0 0 0
126 }
127 } else {
128 3 ▶ $self->SUPER::open($file_name, $mode) or croak "Opening '$file_name' for '$mode' failed: $!";
Branch: 1 branch
BranchTrueFalseTotal
$self->SUPER::open($file_name, $mode) or croak("Opening '${file_name}' for '${mode}' failed: $!") 2 1 3
129 }
130 $data->{id($self)} = {
131 2 %{$data->{id($self)}},
132 @_
133 };
134 2 return $self;
135 };
136
137 =item C<reopen> ( [MODE] )
138
139 Reopen a previously opened file with the same mode or a new mode.
140
141 my $fh = file('test'); #open it for reading;
142 $fh->close;
143 $fh->reopen('a'); #reopen the file for writing.
144
145 =cut
146
147 0 ▶sub reopen {
Subroutine reopen: not called CC=3 SCAR=24.8
Pod documented
148 0 my $self = shift;
149 0 my $data = $data->{id($self)};
150 0 ▶ my $mode = shift || $data->{mode};
Condition0%0/3
shift() || $data->{'mode'}
l!l&&r!l&&!r
000
MC/DC0%0/2
shift() || $data->{'mode'}
shift() $data->{'mode'}
Truth table0%0/3
A || B
A= shift()B= $data->{'mode'}
ABresult
1X1
011
000
151 0 ▶ croak "No file has been opened to be reopened." unless defined $data;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $data 0 0 0
152 0 $self->open($data->{file_name}, $mode);
153 }
154
155 =item C<file> ( FILENAME [,MODE, [OPTIONS]])
156
157 C<file> accepts up to three parameters. If only one is supplied then the
158 default mode is 'read' The mode can be one of 'r',' 'read', 'w', 'write',
159 'a', 'append' which translate to '<', '>', and '>>'. The third parameter
160 is a hash of options. By default C<autochomp> is on, but you can use this
161 to disable it if you prefer. which would cause the slurp method to chomp
162 each line in array context. C<irs> shoft for "Input Record Seperator" lets
163 you set a default value for C<$\> that will be used for C<readline> and
164 C<slurp> operations.
165
166 my $read = file('test');
167 my $write = file('test', 'w');
168
169 my $not_chomped = file('test', 'r', autochomp => 0)
170 my @lines = $not_chomped->slurp();
171
172 my $pipedel = file('test', 'r', irs => '|')
173 my @fields = $pipedel->slurp();
174
175 =cut
176
177 3 ▶sub file {
Subroutine file: called CC=2 SCAR=7.1
Pod documented
178 3 my $self = new IO::Simple;
179 3 ▶ $self->open(@_) if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 3 0 3
180 2 return $self;
181 }
182
183 =item $fh->close
184
185 Wrapper for IO::Handle close with added error handling.
186
187 =cut
188
189 1 ▶sub close {
Subroutine close: called CC=3 SCAR=11.4
Pod documented
190 1 my $self = shift;
191 1 my $data = $data->{id($self)};
192 1 ▶ croak "File '$data->{file_name}' is not open." unless $self->opened;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->opened 0 1 1
193 1 ▶ $self->SUPER::close() or croak "Failed to close '$data->{file_name}' : $!";
Branch: 1 branch
BranchTrueFalseTotal
$self->SUPER::close or croak(qq[Failed to close '$data->{"file_name"}' : $!]) 1 0 1
194 }
195
196 #internal function to wrap functions in error catching
197 0 ▶sub _protect {
Subroutine _protect: not called CC=3 SCAR=24.8
198 0 my $function = shift;
199 0 my $self = shift;
200 0 my $data = $data->{id($self)};
201
202 0 ▶ croak "File '$data->{file_name}' is not opened." unless $self->opened;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->opened 0 0 0
203 0 $" = ',';
204 0 ▶ $self->can("SUPER::$function")->($self,@_) or croak "Failed to $function(@_): $!";
Branch: 1 branch
BranchTrueFalseTotal
$self->can("SUPER::$function")->($self, @_) or croak("Failed to $function(@_): $!") 0 0 0
205 }
206
207 # Protect functions from IO::Seekable
208 0 ▶sub seek { _protect('seek', @_) }
Subroutine seek: not called CC=1 SCAR=6.9
Pod documented
209 0 ▶sub tell { _protect('tell', @_) }
Subroutine tell: not called CC=1 SCAR=6.9
Pod documented
210 0 ▶sub truncate { _protect('truncate', @_) }
Subroutine truncate: not called CC=1 SCAR=6.9
Pod undocumented
211 0 ▶sub sysseek { _protect('sysseek', @_) }
Subroutine sysseek: not called CC=1 SCAR=6.9
Pod documented
212 0 ▶sub setpos { _protect('setpos', @_) }
Subroutine setpos: not called CC=1 SCAR=6.9
Pod documented
213 0 ▶sub getpos { _protect('getpos', @_) }
Subroutine getpos: not called CC=1 SCAR=6.9
Pod documented
214
215
216 =item PerlVar per Handle Methods
217
218 Stores your choice and later localizes the perlvar and sets it appropriately
219 during output operations. Returns current value if no STR is provided.
220
221 $fh->format_line_break_characters( [STR] ) $:
222 $fh->format_formfeed( [STR]) $^L
223 $fh->output_field_separator( [STR] ) $,
224 $fh->output_record_separator( [STR] ) $\
225
226 Stores your choice and later localizes the perlvar and sets it appropriately
227 during input operations. Returns current value if no STR is provided.
228
229 $fh->input_record_separator( [STR] ) $/
230
231
232 =cut
233 0 ▶sub set_option {
Subroutine set_option: not called CC=5 SCAR=34.0
Pod undocumented
234 0 my $self = shift;
235 0 ▶ @_ == 1 || @_ == 2 or croak "usage: \$fh->set_option('option'[ ,value]);";
Branch: 1 branch
BranchTrueFalseTotal
@_ == 1 or @_ == 2 or croak("usage: \$fh->set_option('option'[ ,value]);") 0 0 0
Condition0%0/3
@_ == 1 or @_ == 2
l!l&&r!l&&!r
000
MC/DC0%0/2
@_ == 1 or @_ == 2
@_ == 1 @_ == 2
Truth table0%0/3
A or B
A= @_ == 1B= @_ == 2
ABresult
1X1
011
000
236 0 my $option = shift;
237 0 ▶ return $self->can("SUPER::$option")->(@_) unless ref($self);
Branch: 1 branch
BranchTrueFalseTotal
unless ref $self 0 0 0
238
239 0 my $data = $data->{id($self)};
240 0 ▶ return $data->{$option} unless @_ == 1;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ == 1 0 0 0
241 0 $data->{$option} = shift;
242 }
243
244 0 ▶sub format_line_break_characters { shift->set_option('format_line_break_characters', @_); }
Subroutine format_line_break_characters: not called CC=1 SCAR=6.9
Pod undocumented
245 0 ▶sub format_formfeed { shift->set_option('format_formfeed' , @_); }
Subroutine format_formfeed: not called CC=1 SCAR=6.9
Pod undocumented
246 0 ▶sub output_field_separator { shift->set_option('output_field_separator' , @_); }
Subroutine output_field_separator: not called CC=1 SCAR=6.9
Pod undocumented
247 0 ▶sub output_record_separator { shift->set_option('output_record_separator' , @_); }
Subroutine output_record_separator: not called CC=1 SCAR=6.9
Pod undocumented
248 0 ▶sub input_record_separator { shift->set_option('input_record_separator' , @_); }
Subroutine input_record_separator: not called CC=1 SCAR=6.9
Pod undocumented
249
250
251 =item $fh->print
252
253 Wrapper for IO::Handle C<print> with added error handling and localizes
254 C<$:>, C<$^L>, C<$,>, C<$\> and sets them properly for each file handle.
255
256 =cut
257
258 0 ▶sub say { shift->print(@_,"\n"); }
Subroutine say: not called CC=1 SCAR=6.9
Pod undocumented
259 1 ▶sub print {
Subroutine print: called CC=7 SCAR=21.0
Pod documented
260 1 my $self = shift;
261 1 ▶ croak "File '$data->{file_name}' is not opened." unless $self->opened;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->opened 0 1 1
262 1 my $data = $data->{id($self)};
263
264 1 ▶ local $: = exists $data->{format_line_break_characters} ? $data->{format_line_break_characters} : $:;
Branch: 1 branch
BranchTrueFalseTotal
exists $data->{'format_line_break_characters'} ? : 0 1 1
265 1 ▶ local $^L = exists $data->{format_formfeed} ? $data->{format_formfeed} : $^L;
Branch: 1 branch
BranchTrueFalseTotal
exists $data->{'format_formfeed'} ? : 0 1 1
266 1 ▶ local $, = exists $data->{output_field_separator} ? $data->{output_field_separator} : $,;
Branch: 1 branch
BranchTrueFalseTotal
exists $data->{'output_field_separator'} ? : 0 1 1
267 1 ▶ local $\ = exists $data->{output_record_separator} ? $data->{output_record_separator} : $\;
Branch: 1 branch
BranchTrueFalseTotal
exists $data->{'output_record_separator'} ? : 0 1 1
268
269 1 ▶ print $self @_ or croak "Failed to print to '$data->{file_name}': $!";
Branch: 1 branch
BranchTrueFalseTotal
print $self @_ or croak(qq[Failed to print to '$data->{"file_name"}': $!]) 1 0 1
270 1 return $self;
271 }
272
273 =item IO::Simple::slurp(FILE [,SEP])
274
275 Takes a file name an slurps up the file. In list context it uses the SEP
276 and outputs an array of lines in scalar context it ignores the SEP and
277 returns the entire file in a scalar.
278
279 use IO::Simple qw/slurp/;
280 my $content = slurp('test');
281
282 =item $fh->slurp([SEP])
283
284 C<slurp> returns the remaining contents of the file handle. If used in list
285 context it returns the lines of the file in an array (setting $/ = SEP),
286 otherwise it returns the entire file slurped into a scalar. Unless disablled
287 with autochomp, lines returned in list context will be chomped.
288
289 my $content = file('test')->slurp();
290
291 =cut
292
293 1 ▶sub slurp {
Subroutine slurp: called CC=4 SCAR=15.9
Pod documented
294 1 my $self = shift;
295 1 ▶ unless ($self->isa('IO::Simple')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->isa("IO::Simple")) 0 1 1
296 0 $self = file($self);
297 }
298 1 ▶ croak "File '$data->{file_name}' is not opened." unless $self->opened;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->opened 0 1 1
299 1 ▶ if (wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) { } 0 1 1
300 0 return $self->readline(@_);
301 } else {
302 1 return $self->readline(undef);
303 }
304 }
305
306 1 ▶sub readline {
Subroutine readline: called CC=7 SCAR=24.7
Pod undocumented
307 1 my $self = shift;
308
309 1 my $data = $data->{id($self)};
310 1 ▶ croak "File '$data->{file_name}' is not opened." unless $self->opened;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->opened 0 1 1
311 1 local $/ = $/;
312 1 ▶ if (@_) {
Branch: 2 branches
BranchTrueFalseTotal
if (@_) { } 1 0 1
elsif (exists $data->{'input_record_separator'}) { } 0 0 0
313 1 $/ = shift;
314 } elsif (exists $data->{input_record_separator}) {
315 0 $/ = $data->{input_record_separator};
316 }
317
318 1 ▶ if (wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) { } 0 1 1
319 0 my @lines = <$self>;
320 0 ▶ chomp(@lines) if $data->{autochomp};
Branch: 1 branch
BranchTrueFalseTotal
if $data->{"autochomp"} 0 0 0
321 0 return @lines;
322 } else {
323 1 my $line = <$self>;
324 1 ▶ chomp($line) if $data->{autochomp};;
Branch: 1 branch
BranchTrueFalseTotal
if $data->{"autochomp"} 1 0 1
325 1 return $line;
326 }
327 }
328
329 3 ▶sub DESTROY {
Subroutine DESTROY: called CC=1 SCAR=0.0
330 3 my $self = shift;
331 3 delete $data->{id($self)};
332 }
333
334 1 1;
335
336 =back
337
338 =head1 EXPORT
339
340 Optionaly exports two functions C<file> and C<slurp> or use C<:all> to
341 import both. No methods are exported by default.
342
343 =head1 CAVEAT
344
345 The error checking only works when you use the object methods. This
346 allows you to use the builtins when wish to handle your own error checking.
347
348 my $fh = file('test.txt');
349 $fh->print("Hello Wolrd"); #results in error
350 print $fh "Hello World"; #doesn't through error.
351
352 my $fh = new IO::Simple;
353 $fh->open('test'); #throws error if test doesn't exist
354 open($fh, '<', 'test'); #allows you to handle errors on your own.
355
356 If you don't use the open method the errors will not know which file you
357 opened or what mode you opened it in.
358
359 =head1 SEE ALSO
360
361 L<IO::All>,
362 L<IO::File>,
363 L<Perl6::Slurp>,
364 L<File::Slurp>,
365 L<Fatal>
366
367 =head1 AUTHOR
368
369 Eric Hodges <eric256@gmail.com>
370
371 =head1 COPYRIGHT AND LICENSE
372
373 Copyright (C) 2007 by Eric Hodges
374
375 This library is free software; you can redistribute it and/or modify
376 it under the same terms as Perl itself, either Perl version 5.8.8 or,
377 at your option, any later version of Perl 5 you may have available.
378
379
380 =cut
↑ Summary