File Coverage

inc/File/Slurp.pm
Criterion Covered Total %
statement 57 179 31.8
branch 17 92 18.4
condition 3 20 15.0
subroutine 9 13 69.2
pod 4 4 100.0
total 90 308 29.2


line stmt bran cond sub pod time code
1             #line 1
2             package File::Slurp;
3 1     1   861  
  1         1  
  1         33  
4             use strict;
5 1     1   5  
  1         2  
  1         78  
6 1     1   726 use Carp ;
  1         7052  
  1         8  
7 1     1   1703 use POSIX qw( :fcntl_h ) ;
  1         3  
  1         715  
8 1     1   907 use Fcntl qw( :DEFAULT ) ;
  1         1116  
  1         453  
9             use Symbol ;
10              
11             my $is_win32 = $^O =~ /win32/i ;
12              
13             # Install subs for various constants that aren't set in older perls
14             # (< 5.005). Fcntl on old perls uses Exporter to define subs without a
15             # () prototype These can't be overridden with the constant pragma or
16             # we get a prototype mismatch. Hence this less than aesthetically
17             # appealing BEGIN block:
18              
19 1 50   1   3 BEGIN {
  1         7  
20 0         0 unless( eval { defined SEEK_SET() } ) {
  0         0  
21 0         0 *SEEK_SET = sub { 0 };
  0         0  
22 0         0 *SEEK_CUR = sub { 1 };
  0         0  
23             *SEEK_END = sub { 2 };
24             }
25 1 50       3  
  1         7  
26 0         0 unless( eval { defined O_BINARY() } ) {
  0         0  
27 0         0 *O_BINARY = sub { 0 };
  0         0  
28 0         0 *O_RDONLY = sub { 0 };
  0         0  
29             *O_WRONLY = sub { 1 };
30             }
31 1 50       4  
  1         30  
32             unless ( eval { defined O_APPEND() } ) {
33 0 0       0  
    0          
    0          
34 0         0 if ( $^O =~ /olaris/ ) {
  0         0  
35 0         0 *O_APPEND = sub { 8 };
  0         0  
36 0         0 *O_CREAT = sub { 256 };
  0         0  
37             *O_EXCL = sub { 1024 };
38             }
39 0         0 elsif ( $^O =~ /inux/ ) {
  0         0  
40 0         0 *O_APPEND = sub { 1024 };
  0         0  
41 0         0 *O_CREAT = sub { 64 };
  0         0  
42             *O_EXCL = sub { 128 };
43             }
44 0         0 elsif ( $^O =~ /BSD/i ) {
  0         0  
45 0         0 *O_APPEND = sub { 8 };
  0         0  
46 0         0 *O_CREAT = sub { 512 };
  0         0  
47             *O_EXCL = sub { 2048 };
48             }
49             }
50             }
51              
52             # print "OS [$^O]\n" ;
53              
54             # print "O_BINARY = ", O_BINARY(), "\n" ;
55             # print "O_RDONLY = ", O_RDONLY(), "\n" ;
56             # print "O_WRONLY = ", O_WRONLY(), "\n" ;
57             # print "O_APPEND = ", O_APPEND(), "\n" ;
58             # print "O_CREAT ", O_CREAT(), "\n" ;
59             # print "O_EXCL ", O_EXCL(), "\n" ;
60 1     1   8  
  1         2  
  1         131  
61 1     1   7 use base 'Exporter' ;
  1         1  
  1         1757  
62             use vars qw( %EXPORT_TAGS @EXPORT_OK $VERSION @EXPORT ) ;
63              
64             %EXPORT_TAGS = ( 'all' => [
65             qw( read_file write_file overwrite_file append_file read_dir ) ] ) ;
66              
67             @EXPORT = ( @{ $EXPORT_TAGS{'all'} } );
68             @EXPORT_OK = qw( slurp ) ;
69              
70             $VERSION = '9999.12';
71              
72             *slurp = \&read_file ;
73              
74             sub read_file {
75 6     6 1 646  
76             my( $file_name, %args ) = @_ ;
77              
78             # set the buffer to either the passed in one or ours and init it to the null
79             # string
80 6         9  
81 6   50     31 my $buf ;
82 6         8 my $buf_ref = $args{'buf_ref'} || \$buf ;
  6         12  
83             ${$buf_ref} = '' ;
84 6         12  
85             my( $read_fh, $size_left, $blk_size ) ;
86              
87             # check if we are reading from a handle (glob ref or IO:: object)
88 6 50       17  
89             if ( ref $file_name ) {
90              
91             # slurping a handle so use it and don't open anything.
92             # set the block size so we know it is a handle and read that amount
93 0         0  
94 0   0     0 $read_fh = $file_name ;
95 0         0 $blk_size = $args{'blk_size'} || 1024 * 1024 ;
96             $size_left = $blk_size ;
97              
98             # DEEP DARK MAGIC. this checks the UNTAINT IO flag of a
99             # glob/handle. only the DATA handle is untainted (since it is from
100             # trusted data in the source file). this allows us to test if this is
101             # the DATA handle and then to do a sysseek to make sure it gets
102             # slurped correctly. on some systems, the buffered i/o pointer is not
103             # left at the same place as the fd pointer. this sysseek makes them
104             # the same so slurping with sysread will work.
105 0         0  
  0         0  
106             eval{ require B } ;
107 0 0       0  
108             if ( $@ ) {
109 0         0  
110             @_ = ( \%args, <
111             Can't find B.pm with this Perl: $!.
112             That module is needed to slurp the DATA handle.
113 0         0 ERR
114             goto &_error ;
115             }
116 0 0       0  
117             if ( B::svref_2object( $read_fh )->IO->IoFLAGS & 16 ) {
118              
119             # set the seek position to the current tell.
120 0 0       0  
121             sysseek( $read_fh, tell( $read_fh ), SEEK_SET ) ||
122             croak "sysseek $!" ;
123             }
124             }
125             else {
126              
127             # a regular file. set the sysopen mode
128 6         9  
129             my $mode = O_RDONLY ;
130              
131             #printf "RD: BINARY %x MODE %x\n", O_BINARY, $mode ;
132              
133             # open the file and handle any error
134 6         21  
135 6 50       336 $read_fh = gensym ;
136 0         0 unless ( sysopen( $read_fh, $file_name, $mode ) ) {
137 0         0 @_ = ( \%args, "read_file '$file_name' - sysopen: $!");
138             goto &_error ;
139             }
140 6 50       21  
141             binmode($read_fh, $args{'binmode'}) if $args{'binmode'};
142              
143             # get the size of the file for use in the read loop
144 6         54  
145             $size_left = -s $read_fh ;
146 6 50       18  
147             unless( $size_left ) {
148 0   0     0  
149 0         0 $blk_size = $args{'blk_size'} || 1024 * 1024 ;
150             $size_left = $blk_size ;
151             }
152             }
153              
154             # infinite read loop. we exit when we are done slurping
155 6         7  
156             while( 1 ) {
157              
158             # do the read and see how much we got
159 6         9  
  6         55  
160 6         10 my $read_cnt = sysread( $read_fh, ${$buf_ref},
161             $size_left, length ${$buf_ref} ) ;
162 6 50       16  
163             if ( defined $read_cnt ) {
164              
165             # good read. see if we hit EOF (nothing left to read)
166 6 50       15  
167             last if $read_cnt == 0 ;
168              
169             # loop if we are slurping a handle. we don't track $size_left then.
170 6 50       85  
171             next if $blk_size ;
172              
173 6         10 # count down how much we read and loop if we have more to read.
174 6 50       18 $size_left -= $read_cnt ;
175 0         0 last if $size_left <= 0 ;
176             next ;
177             }
178              
179             # handle the read error
180 0         0  
181 0         0 @_ = ( \%args, "read_file '$file_name' - sysread: $!");
182             goto &_error ;
183             }
184              
185             # fix up cr/lf to be a newline if this is a windows text file
186 6 50 33     17  
  0         0  
187             ${$buf_ref} =~ s/\015\012/\n/g if $is_win32 && !$args{'binmode'} ;
188              
189             # this is the 5 returns in a row. each handles one possible
190             # combination of caller context and requested return type
191 6         13  
192 6 50 33     39 my $sep = $/ ;
193             $sep = '\n\n+' if defined $sep && $sep eq '' ;
194              
195             # caller wants to get an array ref of lines
196              
197             # this split doesn't work since it tries to use variable length lookbehind
198             # the m// line works.
199 6 0       15 # return [ split( m|(?<=$sep)|, ${$buf_ref} ) ] if $args{'array_ref'} ;
  0 50       0  
  0         0  
200             return [ length(${$buf_ref}) ? ${$buf_ref} =~ /(.*?$sep|.+)/sg : () ]
201             if $args{'array_ref'} ;
202              
203             # caller wants a list of lines (normal list context)
204              
205             # same problem with this split as before.
206 6 0       14 # return split( m|(?<=$sep)|, ${$buf_ref} ) if wantarray ;
  0 50       0  
  0         0  
207             return length(${$buf_ref}) ? ${$buf_ref} =~ /(.*?$sep|.+)/sg : ()
208             if wantarray ;
209              
210             # caller wants a scalar ref to the slurped text
211 6 50       17  
212             return $buf_ref if $args{'scalar_ref'} ;
213              
214             # caller wants a scalar with the slurped text (normal scalar context)
215 6 50       13  
  6         91  
216             return ${$buf_ref} if defined wantarray ;
217              
218             # caller passed in an i/o buffer by reference (normal void context)
219 0            
220             return ;
221             }
222              
223             sub write_file {
224 0     0 1    
225             my $file_name = shift ;
226              
227             # get the optional argument hash ref from @_ or an empty hash ref.
228 0 0          
229             my $args = ( ref $_[0] eq 'HASH' ) ? shift : {} ;
230 0            
231             my( $buf_ref, $write_fh, $no_truncate, $orig_file_name, $data_is_ref ) ;
232              
233             # get the buffer ref - it depends on how the data is passed into write_file
234             # after this if/else $buf_ref will have a scalar ref to the data.
235 0 0          
    0          
    0          
236             if ( ref $args->{'buf_ref'} eq 'SCALAR' ) {
237              
238             # a scalar ref passed in %args has the data
239             # note that the data was passed by ref
240 0            
241 0           $buf_ref = $args->{'buf_ref'} ;
242             $data_is_ref = 1 ;
243             }
244             elsif ( ref $_[0] eq 'SCALAR' ) {
245              
246             # the first value in @_ is the scalar ref to the data
247             # note that the data was passed by ref
248 0            
249 0           $buf_ref = shift ;
250             $data_is_ref = 1 ;
251             }
252             elsif ( ref $_[0] eq 'ARRAY' ) {
253              
254             # the first value in @_ is the array ref to the data so join it.
255 0            
  0            
  0            
256             ${$buf_ref} = join '', @{$_[0]} ;
257             }
258             else {
259              
260             # good old @_ has all the data so join it.
261 0            
  0            
262             ${$buf_ref} = join '', @_ ;
263             }
264              
265             # see if we were passed a open handle to spew to.
266 0 0          
267             if ( ref $file_name ) {
268              
269             # we have a handle. make sure we don't call truncate on it.
270 0            
271 0           $write_fh = $file_name ;
272             $no_truncate = 1 ;
273             }
274             else {
275              
276             # spew to regular file.
277 0 0          
278             if ( $args->{'atomic'} ) {
279              
280             # in atomic mode, we spew to a temp file so make one and save the original
281 0           # file name.
282 0           $orig_file_name = $file_name ;
283             $file_name .= ".$$" ;
284             }
285              
286             # set the mode for the sysopen
287 0            
288 0 0         my $mode = O_WRONLY | O_CREAT ;
289 0 0         $mode |= O_APPEND if $args->{'append'} ;
290             $mode |= O_EXCL if $args->{'no_clobber'} ;
291              
292             #printf "WR: BINARY %x MODE %x\n", O_BINARY, $mode ;
293              
294             # open the file and handle any error.
295 0            
296 0 0         $write_fh = gensym ;
297 0           unless ( sysopen( $write_fh, $file_name, $mode ) ) {
298 0           @_ = ( $args, "write_file '$file_name' - sysopen: $!");
299             goto &_error ;
300             }
301 0 0          
302             binmode($write_fh, $args->{'binmode'}) if $args->{'binmode'};
303             }
304 0 0          
305             sysseek( $write_fh, 0, SEEK_END ) if $args->{'append'} ;
306              
307              
308             #print 'WR before data ', unpack( 'H*', ${$buf_ref}), "\n" ;
309              
310             # fix up newline to write cr/lf if this is a windows text file
311 0 0 0        
312             if ( $is_win32 && !$args->{'binmode'} ) {
313              
314             # copy the write data if it was passed by ref so we don't clobber the
315 0 0         # caller's data
  0            
  0            
316 0           $buf_ref = \do{ my $copy = ${$buf_ref}; } if $data_is_ref ;
  0            
317             ${$buf_ref} =~ s/\n/\015\012/g ;
318             }
319              
320             #print 'after data ', unpack( 'H*', ${$buf_ref}), "\n" ;
321              
322             # get the size of how much we are writing and init the offset into that buffer
323 0            
  0            
324 0           my $size_left = length( ${$buf_ref} ) ;
325             my $offset = 0 ;
326              
327             # loop until we have no more data left to write
328 0            
329             do {
330              
331             # do the write and track how much we just wrote
332 0            
  0            
333             my $write_cnt = syswrite( $write_fh, ${$buf_ref},
334             $size_left, $offset ) ;
335 0 0          
336             unless ( defined $write_cnt ) {
337              
338 0           # the write failed
339 0           @_ = ( $args, "write_file '$file_name' - syswrite: $!");
340             goto &_error ;
341             }
342              
343             # track much left to write and where to write from in the buffer
344 0            
345 0           $size_left -= $write_cnt ;
346             $offset += $write_cnt ;
347              
348             } while( $size_left > 0 ) ;
349              
350             # we truncate regular files in case we overwrite a long file with a shorter file
351             # so seek to the current position to get it (same as tell()).
352 0 0          
353             truncate( $write_fh,
354             sysseek( $write_fh, 0, SEEK_CUR ) ) unless $no_truncate ;
355 0            
356             close( $write_fh ) ;
357              
358             # handle the atomic mode - move the temp file to the original filename.
359 0 0          
360             rename( $file_name, $orig_file_name ) if $args->{'atomic'} ;
361 0            
362             return 1 ;
363             }
364              
365             # this is for backwards compatibility with the previous File::Slurp module.
366             # write_file always overwrites an existing file
367              
368             *overwrite_file = \&write_file ;
369              
370             # the current write_file has an append mode so we use that. this
371             # supports the same API with an optional second argument which is a
372             # hash ref of options.
373              
374             sub append_file {
375              
376 0     0 1   # get the optional args hash ref
377 0 0         my $args = $_[1] ;
378             if ( ref $args eq 'HASH' ) {
379              
380             # we were passed an args ref so just mark the append mode
381 0            
382             $args->{append} = 1 ;
383             }
384             else {
385              
386             # no args hash so insert one with the append mode
387 0            
388             splice( @_, 1, 0, { append => 1 } ) ;
389             }
390              
391             # magic goto the main write_file sub. this overlays the sub without touching
392             # the stack or @_
393 0            
394             goto &write_file
395             }
396              
397             # basic wrapper around opendir/readdir
398              
399             sub read_dir {
400 0     0 1    
401             my ($dir, %args ) = @_;
402              
403             # this handle will be destroyed upon return
404 0            
405             local(*DIRH);
406              
407             # open the dir and handle any errors
408 0 0          
409             unless ( opendir( DIRH, $dir ) ) {
410 0            
411 0           @_ = ( \%args, "read_dir '$dir' - opendir: $!" ) ;
412             goto &_error ;
413             }
414 0            
415             my @dir_entries = readdir(DIRH) ;
416 0 0 0        
417             @dir_entries = grep( $_ ne "." && $_ ne "..", @dir_entries )
418             unless $args{'keep_dot_dot'} ;
419 0 0          
420 0           return @dir_entries if wantarray ;
421             return \@dir_entries ;
422             }
423              
424             # error handling section
425             #
426             # all the error handling uses magic goto so the caller will get the
427             # error message as if from their code and not this module. if we just
428             # did a call on the error code, the carp/croak would report it from
429             # this module since the error sub is one level down on the call stack
430             # from read_file/write_file/read_dir.
431              
432              
433             my %err_func = (
434             'carp' => \&carp,
435             'croak' => \&croak,
436             ) ;
437              
438             sub _error {
439 0     0      
440             my( $args, $err_msg ) = @_ ;
441              
442             # get the error function to use
443 0   0        
444             my $func = $err_func{ $args->{'err_mode'} || 'croak' } ;
445              
446             # if we didn't find it in our error function hash, they must have set
447             # it to quiet and we don't do anything.
448 0 0          
449             return unless $func ;
450              
451             # call the carp/croak function
452 0            
453             $func->($err_msg) ;
454              
455             # return a hard undef (in list context this will be a single value of
456             # undef which is not a legal in-band value)
457 0            
458             return undef ;
459             }
460              
461             1;
462             __END__