blib/lib/File/LoadLines.pm

filter: Statementstmt 63.3% 95 / 150 Branchbran 59.8% 61 / 102 Conditioncond 53.3% 16 / 30 MC/DCmcdc 27.7% 5 / 18 Subroutinesub 100% 8 / 8 Podpod 100% 2 / 2 totaltotal 60.3% 187 / 310 CC 64 SCAR 56.7
CC
64
Cov
61%
loadlines
343.4
loadblob
5.9
BEGIN
1.0
CRAP 290.7
↑ Summary
1 #! perl
2  
3 package File::LoadLines;
4  
5 14 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 14 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 14 ▶use Exporter qw(import);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 14 our @EXPORT = qw( loadlines );
9 14 our @EXPORT_OK = qw( loadblob );
10 14 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 14 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 14 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 =head1 NAME
15  
16 File::LoadLines - Load lines from files and network
17  
18 =cut
19  
20 14 our $VERSION = '1.047';
21  
22 =head1 SYNOPSIS
23  
24 use File::LoadLines;
25 my @lines = loadlines("mydata.txt");
26  
27 use File::LoadLines qw(loadblob);
28 my $img = loadblob("https://img.shields.io/badge/Language-Perl-blue");
29  
30 =head1 DESCRIPTION
31  
32 File::LoadLines provides an easy way to load the contents of a text
33 file into an array of lines. It is intended for small to moderate size files
34 like config files that are often produced by weird tools (and users).
35  
36 It will transparently fetch data from the network if the provided file
37 name is a URL.
38  
39 File::LoadLines automatically handles ASCII, Latin-1 and UTF-8 text.
40 When the file has a BOM, it handles UTF-8, UTF-16 LE and BE, and
41 UTF-32 LE and BE.
42  
43 Recognized line terminators are NL (Unix, Linux), CRLF (DOS, Windows)
44 and CR (Mac)
45  
46 Function loadblob(), exported on depand, fetches the content and
47 returns it without processing, equivalent to File::Slurp and ilk.
48  
49 =head1 EXPORT
50  
51 By default the function loadlines() is exported.
52  
53 =head1 FUNCTIONS
54  
55 =head2 loadlines
56  
57 @lines = loadlines("mydata.txt");
58 @lines = loadlines("mydata.txt", $options);
59  
60 The file is opened, read, decoded and split into lines
61 that are returned in the result array. Line terminators are removed.
62  
63 In scalar context, returns an array reference.
64  
65 The first argument may be the name of a file, an opened file handle,
66 or a reference to a string that contains the data.
67 The name of a file on disk may start with C<"file://">, this is ignored.
68 If the name starts with C<"http:"> or C<"https:"> the data will be
69 retrieved using LWP.
70 L<Data URLs|https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs> like C<"data:text/plain;base64,SGVsbG8sIFdvcmxkIQ=="> are
71 also supported.
72  
73 The second argument can be used to influence the behaviour.
74 It is a hash reference of option settings.
75  
76 Note that loadlines() is a I<slurper>, it reads the whole file into
77 memory and, for splitting, requires temporarily memory for twice the
78 size of the file.
79  
80 =over
81  
82 =item split
83  
84 Enabled by default.
85  
86 The data is split into lines and returned as an array (in list
87 context) or as an array reference (in scalar context).
88  
89 If set to zero, the data is not split into lines but returned as a
90 single string.
91  
92 =item chomp
93  
94 Enabled by default.
95  
96 Line terminators are removed from the resultant lines.
97  
98 If set to zero, the line terminators are not removed.
99  
100 =item encoding
101  
102 If specified, loadlines() will use this encoding to decode the file
103 data if it cannot automatically detect the encoding.
104  
105 If you pass an options hash, File::LoadLines will set C<encoding> to
106 the encoding it detected and used for this file data.
107  
108 =item blob
109  
110 If specified, the data read is not touched but returned exactly as read.
111  
112 C<blob> overrules C<split> and C<chomp>.
113  
114 =item fail
115  
116 If specified, it should be either C<"hard"> or C<"soft">.
117  
118 If C<"hard">, read errors are signalled using croak exceptions.
119 This is the default.
120  
121 If set to C<"soft">, loadlines() will return an empty result and set
122 the error message in the options hash with key C<"error">.
123  
124 =back
125  
126 =cut
127  
128 70 ▶sub loadlines {
Subroutine loadlines: called CC=60 SCAR=58.4
Pod documented
129 70 my ( $filename, $options ) = @_;
130 70 ▶ croak("Missing filename.\n") unless defined $filename;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $filename 1 69 70
131 69 ▶ croak("Invalid options.\n") if (defined $options && (ref($options) ne "HASH"));
Branch: 1 branch
BranchTrueFalseTotal
if defined $options and ref $options ne "HASH" 1 68 69
Condition100%3/3
defined $options and ref $options ne "HASH"
!ll&&!rl&&r
18501
MC/DC100%2/2
defined $options and ref $options ne "HASH"
defined $options ref $options ne "HASH"
Truth table100%3/3
A and B
A= defined $optionsB= ref $options ne "HASH"
ABresult
0X0
100
111
132  
133 68 ▶ $options->{blob} //= 0;
Condition100%2/2
$options->{"blob"} //= 0
l!l
464
MC/DC100%1/1
$options->{"blob"} //= 0
$options->{"blob"}
Truth table100%2/2
A
A= $options->{"blob"}
Aresult
11
00
134 68 ▶ $options->{split} //= !$options->{blob};
Condition50%1/2
$options->{"split"} //= !$options->{"blob"}
l!l
068
MC/DC0%0/1
$options->{"split"} //= !$options->{"blob"}
$options->{"split"}
Truth table50%1/2
A
A= $options->{"split"}
Aresult
11
00
135 68 ▶ $options->{chomp} //= !$options->{blob};
Condition100%2/2
$options->{"chomp"} //= !$options->{"blob"}
l!l
1256
MC/DC100%1/1
$options->{"chomp"} //= !$options->{"blob"}
$options->{"chomp"}
Truth table100%2/2
A
A= $options->{"chomp"}
Aresult
11
00
136 68 ▶ $options->{fail} //= "hard";
Condition100%2/2
$options->{"fail"} //= "hard"
l!l
2939
MC/DC100%1/1
$options->{"fail"} //= "hard"
$options->{"fail"}
Truth table100%2/2
A
A= $options->{"fail"}
Aresult
11
00
137  
138 68 my $data; # slurped file data
139 my $encoded; # already encoded
140  
141 # Gather data from the input.
142 68 ▶ if ( ref($filename) ) {
Branch: 4 branches
BranchTrueFalseTotal
if (ref $filename) { } 7 61 68
elsif ($filename eq '-') { } 0 61 61
elsif ($filename =~ /^https?:/) { } 0 61 61
elsif ($filename =~ /^data:/) { } 0 61 61
143 7 ▶ if ( ref($filename) eq 'GLOB' || ref($filename) eq 'IO::File' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $filename eq 'GLOB' or ref $filename eq 'IO::File') { } 0 7 7
Condition33%1/3
ref $filename eq "GLOB" or ref $filename eq "IO::File"
l!l&&r!l&&!r
007
MC/DC0%0/2
ref $filename eq "GLOB" or ref $filename eq "IO::File"
ref $filename eq "GLOB" ref $filename eq "IO::File"
Truth table33%1/3
A or B
A= ref $filename eq "GLOB"B= ref $filename eq "IO::File"
ABresult
1X1
011
000
144 0 binmode( $filename, ':raw' );
145 0 $data = do { local $/; <$filename> };
146 0 $filename = "__GLOB__";
147 }
148 else {
149 7 $data = $$filename;
150 7 $filename = "__STRING__";
151 7 $encoded++;
152 }
153 }
154 elsif ( $filename eq '-' ) {
155 0 $filename = "__STDIN__";
156 0 binmode( STDIN, ':raw' );
157 0 $data = do { local $/; <STDIN> };
158 }
159 elsif ( $filename =~ /^https?:/ ) {
160 0 require LWP::UserAgent;
161 0 my $ua = LWP::UserAgent->new( timeout => 20 );
162 0 my $res = $ua->get($filename);
163 0 ▶ if ( $res->is_success ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($res->is_success) { } 0 0 0
elsif ($options->{'fail'} eq 'soft') { } 0 0 0
164 0 $data = $res->decoded_content;
165 }
166 elsif ( $options->{fail} eq "soft" ) {
167 0 $options->{error} = $res->status_line;
168 0 return;
169 }
170 else {
171 0 croak("$filename: ", $res->status_line);
172 }
173 }
174 elsif ( $filename =~ /^data:/ ) {
175 0 ▶ unless ( $filename =~ m! ^ data:
Branch: 1 branch
BranchTrueFalseTotal
unless ($filename =~ / ^ data: (?<mediatype> .*? ) , (?<data> .* ) $ /sx) 0 0 0
176 (?<mediatype> .*? )
177 ,
178 (?<data> .* ) $
179 !sx ) {
180 0 ▶ if ( $options->{fail} eq "soft" ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{'fail'} eq 'soft') { } 0 0 0
181 0 $options->{error} = "Malformed inline data";
182 0 return;
183 }
184 else {
185 0 croak("Malformed inline data");
186 }
187 }
188 0 $data = $+{data};
189 0 $filename = "__DATA__";
190 0 my $mediatype = $+{mediatype};
191 0 my $enc = "";
192 0 ▶ if ( $mediatype && $mediatype =~ /^(.*);base64$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mediatype and $mediatype =~ /^(.*);base64$/) 0 0 0
Condition0%0/3
$mediatype and $mediatype =~ /^(.*);base64$/
!ll&&!rl&&r
000
MC/DC0%0/2
$mediatype and $mediatype =~ /^(.*);base64$/
$mediatype $mediatype =~ /^(.*);base64$/
Truth table0%0/3
A and B
A= $mediatypeB= $mediatype =~ /^(.*);base64$/
ABresult
0X0
100
111
193 0 $mediatype = $1;
194 0 $enc = "base64";
195 }
196 0 ▶ $options->{mediatype} = $mediatype if $mediatype;
Branch: 1 branch
BranchTrueFalseTotal
if $mediatype 0 0 0
197 0 ▶ if ( ! $enc ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $enc) { } 0 0 0
198 # URL encoded.
199 0 $data = $+{data};
200 0 $data =~ s/\%([0-9a-f][0-9a-f])/chr(hex($1))/ige;
201 }
202 else {
203 # Base64.
204 0 require MIME::Base64;
205 0 $data = MIME::Base64::decode($data);
206 }
207 0 ▶ if ( $mediatype && $mediatype =~ /;charset=([^;]*)/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mediatype and $mediatype =~ /;charset=([^;]*)/) 0 0 0
Condition0%0/3
$mediatype and $mediatype =~ /;charset=([^;]*)/
!ll&&!rl&&r
000
MC/DC0%0/2
$mediatype and $mediatype =~ /;charset=([^;]*)/
$mediatype $mediatype =~ /;charset=([^;]*)/
Truth table0%0/3
A and B
A= $mediatypeB= $mediatype =~ /;charset=([^;]*)/
ABresult
0X0
100
111
208 0 $data = decode( $1, $data );
209 0 $options->{encoding} = $1;
210 0 $encoded++;
211 }
212 }
213 else {
214 61 my $name = $filename;
215 61 $name =~ s;^file://;;;
216 61 $filename = decode_utf8($name);
217 # On MS Windows, non-latin (wide) filenames need special treatment.
218 61 ▶ if ( $filename ne $name && $^O =~ /mswin/i ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($filename ne $name and $^O =~ /mswin/i) { } 0 61 61
Condition66%2/3
$filename ne $name and $^O =~ /mswin/i
!ll&&!rl&&r
6010
MC/DC0%0/2
$filename ne $name and $^O =~ /mswin/i
$filename ne $name $^O =~ /mswin/i
Truth table66%2/3
A and B
A= $filename ne $nameB= $^O =~ /mswin/i
ABresult
0X0
100
111
219 0 require Win32API::File;
220 0 my $fn = encode('UTF-16LE', "$filename").chr(0).chr(0);
221 0 my $fh = Win32API::File::CreateFileW
222 ( $fn, Win32API::File::FILE_READ_DATA(), 0, [],
223 Win32API::File::OPEN_EXISTING(), 0, []);
224 0 ▶ croak("$filename: $^E (Win32)\n") if $^E;
Branch: 1 branch
BranchTrueFalseTotal
if $^E 0 0 0
225 0 ▶ unless ( Win32API::File::OsFHandleOpen( 'FILE', $fh, "r") ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (Win32API::File::OsFHandleOpen("FILE", $fh, "r")) 0 0 0
226 0 ▶ $options->{error} = "$!", return if $options->{fail} eq "soft";
Branch: 1 branch
BranchTrueFalseTotal
if $options->{"fail"} eq "soft" 0 0 0
227 0 croak("$filename: $!\n");
228 }
229 0 binmode FILE => ':raw';
230 0 $data = do { local $/; readline(\*FILE) };
231 # warn("$filename³: len=", length($data), "\n");
232 0 close(FILE);
233 }
234 else {
235 61 my $f;
236 61 ▶ unless ( open( $f, '<:raw', $filename ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (open $f, "<:raw", $filename) 1 60 61
237 $options->{error} = "$!", return
238 1 ▶ if $options->{fail} eq "soft";
Branch: 1 branch
BranchTrueFalseTotal
if $options->{"fail"} eq "soft" 1 0 1
239 0 croak("$name: $!\n");
240 }
241 60 $data = do { local $/; <$f> };
242 }
243 }
244 67 ▶ $options->{_filesource} = $filename if $options;
Branch: 1 branch
BranchTrueFalseTotal
if $options 67 0 67
245  
246 67 my $name = encode_utf8($filename);
247 67 ▶ if ( $options->{blob} ) {
Branch: 8 branches
BranchTrueFalseTotal
if ($options->{'blob'}) { } 4 63 67
elsif ($encoded) { } 3 60 63
elsif ($data =~ /^\xEF\xBB\xBF/) { } 13 47 60
elsif ($data =~ /^\xFE\xFF/) { } 4 43 47
elsif ($data =~ /^\xFF\xFE\x00\x00/) { } 4 39 43
elsif ($data =~ /^\xFF\xFE/) { } 13 26 39
elsif ($data =~ /^\x00\x00\xFE\xFF/) { } 4 22 26
elsif ($options->{'encoding'}) { } 1 21 22
248 # Do not touch.
249 4 $options->{encoding} = 'Blob';
250 }
251 elsif ( $encoded ) {
252 # Nothing to do, already dealt with.
253 3 ▶ $options->{encoding} //= 'Perl';
Condition50%1/2
$options->{"encoding"} //= "Perl"
l!l
03
MC/DC0%0/1
$options->{"encoding"} //= "Perl"
$options->{"encoding"}
Truth table50%1/2
A
A= $options->{"encoding"}
Aresult
11
00
254 }
255  
256 # Detect Byte Order Mark.
257 elsif ( $data =~ /^\xEF\xBB\xBF/ ) {
258 13 ▶ warn("$name is UTF-8 (BOM)\n") if $options->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $options->{"debug"} 0 13 13
259 13 $options->{encoding} = 'UTF-8';
260 13 $data = decode( "UTF-8", substr($data, 3) );
261 }
262 elsif ( $data =~ /^\xFE\xFF/ ) {
263 4 ▶ warn("$name is UTF-16BE (BOM)\n") if $options->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $options->{"debug"} 0 4 4
264 4 $options->{encoding} = 'UTF-16BE';
265 4 $data = decode( "UTF-16BE", substr($data, 2) );
266 }
267 elsif ( $data =~ /^\xFF\xFE\x00\x00/ ) {
268 4 ▶ warn("$name is UTF-32LE (BOM)\n") if $options->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $options->{"debug"} 0 4 4
269 4 $options->{encoding} = 'UTF-32LE';
270 4 $data = decode( "UTF-32LE", substr($data, 4) );
271 }
272 elsif ( $data =~ /^\xFF\xFE/ ) {
273 13 ▶ warn("$name is UTF-16LE (BOM)\n") if $options->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $options->{"debug"} 0 13 13
274 13 $options->{encoding} = 'UTF-16LE';
275 13 $data = decode( "UTF-16LE", substr($data, 2) );
276 }
277 elsif ( $data =~ /^\x00\x00\xFE\xFF/ ) {
278 4 ▶ warn("$name is UTF-32BE (BOM)\n") if $options->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $options->{"debug"} 0 4 4
279 4 $options->{encoding} = 'UTF-32BE';
280 4 $data = decode( "UTF-32BE", substr($data, 4) );
281 }
282  
283 # No BOM, did user specify an encoding?
284 elsif ( $options->{encoding} ) {
285 warn("$name is ", $options->{encoding}, " (fallback)\n")
286 1 ▶ if $options->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $options->{"debug"} 0 1 1
287 1 $data = decode( $options->{encoding}, $data, 1 );
288 }
289  
290 # Try UTF8, fallback to ISO-8895.1.
291 else {
292 21 my $d = eval { decode( "UTF-8", $data, 1 ) };
293 21 ▶ if ( $@ ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($@) { } 5 16 21
elsif (not $d =~ /[^[:ascii:]]/) { } 2 14 16
294 5 ▶ warn("$name is ISO-8859.1 (assumed)\n") if $options->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $options->{"debug"} 0 5 5
295 5 $options->{encoding} = 'ISO-8859-1';
296 5 $data = decode( "iso-8859-1", $data );
297 }
298 elsif ( $d !~ /[^[:ascii:]]/ ) {
299 2 ▶ warn("$name is ASCII (detected)\n") if $options->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $options->{"debug"} 0 2 2
300 2 $options->{encoding} = 'ASCII';
301 2 $data = $d;
302 }
303 else {
304 14 ▶ warn("$name is UTF-8 (detected)\n") if $options->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $options->{"debug"} 0 14 14
305 14 $options->{encoding} = 'UTF-8';
306 14 $data = $d;
307 }
308 }
309  
310 # This can be used to add line continuation or comment stripping.
311 67 ▶ if ( $options->{strip} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{"strip"}) 0 67 67
312 0 $data =~ s/$options->{strip}//g;
313 }
314  
315 67 ▶ return $data unless $options->{split};
Branch: 1 branch
BranchTrueFalseTotal
unless $options->{"split"} 4 63 67
316  
317 # Split in lines;
318 63 my @lines;
319 63 ▶ if ( $options->{chomp} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options->{'chomp'}) { } 51 12 63
320 # Unless empty, make sure there is a final newline.
321 51 ▶ $data .= "\n" if $data =~ /.(?!\r\n|\n|\r)\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $data =~ /.(?!\r\n|\n|\r)\z/ 13 38 51
322 # We need to maintain trailing newlines.
323 51 ▶ push( @lines, $1 ) while $data =~ /(.*?)(?:\r\n|\n|\r)/g;
Branch: 1 branch
BranchTrueFalseTotal
$data =~ /(.*?)(?:\r\n|\n|\r)/g and do { push @lines, $1 } 142 51 193
324 }
325 else {
326 12 ▶ push( @lines, $1 ) while $data =~ /(.*?(?:\r\n|\n|\r))/g;
Branch: 1 branch
BranchTrueFalseTotal
$data =~ /(.*?(?:\r\n|\n|\r))/g and do { push @lines, $1 } 42 12 54
327 # In case the last line has no terminator.
328 12 ▶ push( @lines, $1 ) if $data =~ /(?:\r\n|\n|\r)([^\r\n]+)\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $data =~ /(?:\r\n|\n|\r)([^\r\n]+)\z/ 3 9 12
329 }
330 63 undef $data;
331 63 ▶ return wantarray ? @lines : \@lines;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 54 9 63
332 }
333  
334 =head2 loadblob
335  
336 use File::LoadLines qw(loadblob);
337 $rawdata = loadblob("raw.dat");
338 $rawdata = loadblob("raw.dat", $options);
339  
340 This is equivalent to calling loadlines() with C<< blob=>1 >> in the options.
341  
342 =cut
343  
344 2 ▶sub loadblob {
Subroutine loadblob: called CC=5 SCAR=17.8
Pod documented
345 2 my ( $filename, $options ) = @_;
346 2 ▶ croak("Missing filename.\n") unless defined $filename;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $filename 0 2 2
347 2 ▶ croak("Invalid options.\n")
Branch: 1 branch
BranchTrueFalseTotal
if defined $options and ref $options ne "HASH" 0 2 2
Condition33%1/3
defined $options and ref $options ne "HASH"
!ll&&!rl&&r
200
MC/DC0%0/2
defined $options and ref $options ne "HASH"
defined $options ref $options ne "HASH"
Truth table33%1/3
A and B
A= defined $optionsB= ref $options ne "HASH"
ABresult
0X0
100
111
348 if defined($options) && ref($options) ne "HASH";
349 2 ▶ $options //= {};
Condition50%1/2
$options //= {}
l!l
02
MC/DC0%0/1
$options //= {}
$options
Truth table50%1/2
A
A= $options
Aresult
11
00
350 2 $options->{blob} = 1;
351 2 loadlines( $filename, $options );
352 }
353  
354 =head1 SEE ALSO
355  
356 There are currently no other modules that handle BOM detection and
357 line splitting.
358  
359 I have a faint hope that future versions of Perl and Raku will deal
360 with this transparently, but I fear the worst.
361  
362 =head1 HINTS
363  
364 When you have raw file data (e.g. from a zip), you can use loadlines()
365 to decode and unpack:
366  
367 open( my $data, '<', \$contents );
368 $lines = loadlines( $data, $options );
369  
370 There is no hard requirement on LWP. If you want to use transparent
371 fetching of data over the network please make sure LWP::UserAgent is
372 available.
373  
374 =head1 AUTHOR
375  
376 Johan Vromans, C<< <JV at cpan.org> >>
377  
378 =head1 SUPPORT AND DOCUMENTATION
379  
380 Development of this module takes place on GitHub:
381 https://github.com/sciurius/perl-File-LoadLines.
382  
383 You can find documentation for this module with the perldoc command.
384  
385 perldoc File::LoadLines
386  
387 Please report any bugs or feature requests using the issue tracker on
388 GitHub.
389  
390 =head1 COPYRIGHT & LICENSE
391  
392 Copyright 2018,2020,2024 Johan Vromans, all rights reserved.
393  
394 This program is free software; you can redistribute it and/or modify it
395 under the same terms as Perl itself.
396  
397 =cut
398  
399 14 1; # End of File::LoadLines
↑ Summary