1File::Slurp(3) User Contributed Perl Documentation File::Slurp(3)
2
3
4
6 File::Slurp - Simple and Efficient Reading/Writing/Modifying of
7 Complete Files
8
10 use File::Slurp;
11
12 # read in a whole file into a scalar
13 my $text = read_file('/path/file');
14
15 # read in a whole file into an array of lines
16 my @lines = read_file('/path/file');
17
18 # write out a whole file from a scalar
19 write_file('/path/file', $text);
20
21 # write out a whole file from an array of lines
22 write_file('/path/file', @lines);
23
24 # Here is a simple and fast way to load and save a simple config file
25 # made of key=value lines.
26 my %conf = read_file('/path/file') =~ /^(\w+)=(.*)$/mg;
27 write_file('/path/file', {atomic => 1}, map "$_=$conf{$_}\n", keys %conf);
28
29 # insert text at the beginning of a file
30 prepend_file('/path/file', $text);
31
32 # in-place edit to replace all 'foo' with 'bar' in file
33 edit_file { s/foo/bar/g } '/path/file';
34
35 # in-place edit to delete all lines with 'foo' from file
36 edit_file_lines sub { $_ = '' if /foo/ }, '/path/file';
37
38 # read in a whole directory of file names (skipping . and ..)
39 my @files = read_dir('/path/to/dir');
40
42 This module provides subs that allow you to read or write entire files
43 with one simple call. They are designed to be simple to use, have
44 flexible ways to pass in or get the file contents and to be very
45 efficient. There is also a sub to read in all the files in a directory.
46
47 WARNING - PENDING DOOM
48 Although you technically can, do NOT use this module to work on file
49 handles, pipes, sockets, standard IO, or the "DATA" handle. These are
50 features implemented long ago that just really shouldn't be abused
51 here.
52
53 Be warned: this activity will lead to inaccurate encoding/decoding of
54 data.
55
56 All further mentions of actions on the above have been removed from
57 this documentation and that feature set will likely be deprecated in
58 the future.
59
60 In other words, if you don't have a filename to pass, consider using
61 the standard "do { local $/; <$fh> }", or
62 Data::Section/Data::Section::Simple for working with "__DATA__".
63
65 File::Slurp implements the following functions.
66
67 append_file
68 use File::Spec qw(append_file write_file);
69 my $res = append_file('/path/file', "Some text");
70 # same as
71 my $res = write_file('/path/file', {append => 1}, "Some text");
72
73 The "append_file" function is simply a synonym for the "write_file" in
74 File::Slurp function, but ensures that the "append" option is set.
75
76 edit_file
77 use File::Slurp qw(edit_file);
78 # perl -0777 -pi -e 's/foo/bar/g' /path/file
79 edit_file { s/foo/bar/g } '/path/file';
80 edit_file sub { s/foo/bar/g }, '/path/file';
81 sub replace_foo { s/foo/bar/g }
82 edit_file \&replace_foo, '/path/file';
83
84 The "edit_file" function reads in a file into $_, executes a code block
85 that should modify $_, and then writes $_ back to the file. The
86 "edit_file" function reads in the entire file and calls the code block
87 one time. It is equivalent to the "-pi" command line options of Perl
88 but you can call it from inside your program and not have to fork out a
89 process.
90
91 The first argument to "edit_file" is a code block or a code reference.
92 The code block is not followed by a comma (as with "grep" and "map")
93 but a code reference is followed by a comma.
94
95 The next argument is the filename.
96
97 The next argument(s) is either a hash reference or a flattened hash,
98 "key => value" pairs. The options are passed through to the
99 "write_file" in File::Slurp function. All options are described there.
100 Only the "binmode" and "err_mode" options are supported. The call to
101 "write_file" in File::Slurp has the "atomic" option set so you will
102 always have a consistent file.
103
104 edit_file_lines
105 use File::Slurp qw(edit_file_lines);
106 # perl -pi -e '$_ = "" if /foo/' /path/file
107 edit_file_lines { $_ = '' if /foo/ } '/path/file';
108 edit_file_lines sub { $_ = '' if /foo/ }, '/path/file';
109 sub delete_foo { $_ = '' if /foo/ }
110 edit_file \&delete_foo, '/path/file';
111
112 The "edit_file_lines" function reads each line of a file into $_, and
113 executes a code block that should modify $_. It will then write $_ back
114 to the file. It is equivalent to the "-pi" command line options of Perl
115 but you can call it from inside your program and not have to fork out a
116 process.
117
118 The first argument to "edit_file_lines" is a code block or a code
119 reference. The code block is not followed by a comma (as with "grep"
120 and "map") but a code reference is followed by a comma.
121
122 The next argument is the filename.
123
124 The next argument(s) is either a hash reference or a flattened hash,
125 "key => value" pairs. The options are passed through to the
126 "write_file" in File::Slurp function. All options are described there.
127 Only the "binmode" and "err_mode" options are supported. The call to
128 "write_file" in File::Slurp has the "atomic" option set so you will
129 always have a consistent file.
130
131 ef
132 use File::Slurp qw(ef);
133 # perl -0777 -pi -e 's/foo/bar/g' /path/file
134 ef { s/foo/bar/g } '/path/file';
135 ef sub { s/foo/bar/g }, '/path/file';
136 sub replace_foo { s/foo/bar/g }
137 ef \&replace_foo, '/path/file';
138
139 The "ef" function is simply a synonym for the "edit_file" in
140 File::Slurp function.
141
142 efl
143 use File::Slurp qw(efl);
144 # perl -pi -e '$_ = "" if /foo/' /path/file
145 efl { $_ = '' if /foo/ } '/path/file';
146 efl sub { $_ = '' if /foo/ }, '/path/file';
147 sub delete_foo { $_ = '' if /foo/ }
148 efl \&delete_foo, '/path/file';
149
150 The "efl" function is simply a synonym for the "edit_file_lines" in
151 File::Slurp function.
152
153 overwrite_file
154 use File::Spec qw(overwrite_file);
155 my $res = overwrite_file('/path/file', "Some text");
156
157 The "overwrite_file" function is simply a synonym for the "write_file"
158 in File::Slurp function.
159
160 prepend_file
161 use File::Slurp qw(prepend_file);
162 prepend_file('/path/file', $header);
163 prepend_file('/path/file', \@lines);
164 prepend_file('/path/file', { binmode => ':raw'}, $bin_data);
165
166 # equivalent to:
167 use File::Slurp qw(read_file write_file);
168 my $content = read_file('/path/file');
169 my $new_content = "hahahaha";
170 write_file('/path/file', $new_content . $content);
171
172 The "prepend_file" function is the opposite of "append_file" in
173 File::Slurp as it writes new contents to the beginning of the file
174 instead of the end. It is a combination of "read_file" in File::Slurp
175 and "write_file" in File::Slurp. It works by first using "read_file" to
176 slurp in the file and then calling "write_file" with the new data and
177 the existing file data.
178
179 The first argument to "prepend_file" is the filename.
180
181 The next argument(s) is either a hash reference or a flattened hash,
182 "key => value" pairs. The options are passed through to the
183 "write_file" in File::Slurp function. All options are described there.
184
185 Only the "binmode" and "err_mode" options are supported. The
186 "write_file" call has the "atomic" option set so you will always have a
187 consistent file.
188
189 read_dir
190 use File::Spec qw(read_dir);
191 my @files = read_dir('/path/to/dir');
192 # all files, even the dots
193 my @files = read_dir('/path/to/dir', keep_dot_dot => 1);
194 # keep the full file path
195 my @paths = read_dir('/path/to/dir', prefix => 1);
196 # scalar context
197 my $files_ref = read_dir('/path/to/dir');
198
199 This function returns a list of the filenames in the supplied
200 directory. In list context, an array is returned, in scalar context, an
201 array reference is returned.
202
203 The first argument is the path to the directory to read.
204
205 The next argument(s) is either a hash reference or a flattened hash,
206 "key => value" pairs. The following options are available:
207
208 · err_mode
209
210 The "err_mode" option has three possible values: "quiet", "carp",
211 or the default, "croak". In "quiet" mode, all errors will be
212 silent. In "carp" mode, all errors will be emitted as warnings.
213 And, in "croak" mode, all errors will be emitted as exceptions.
214 Take a look at Try::Tiny or Syntax::Keyword::Try to see how to
215 catch exceptions.
216
217 · keep_dot_dot
218
219 The "keep_dot_dot" option is a boolean option, defaulted to false
220 (0). Setting this option to true (1) will also return the "." and
221 ".." files that are removed from the file list by default.
222
223 · prefix
224
225 The "prefix" option is a boolean option, defaulted to false (0).
226 Setting this option to true (1) add the directory as a prefix to
227 the file. The directory and the filename are joined using
228 "File::Spec->catfile()" to ensure the proper directory separator is
229 used for your OS. See File::Spec.
230
231 read_file
232 use File::Slurp qw(read_file);
233 my $text = read_file('/path/file');
234 my $bin = read_file('/path/file', { binmode => ':raw' });
235 my @lines = read_file('/path/file');
236 my $lines_ref = read_file('/path/file', array_ref => 1);
237 my $lines_ref = [ read_file('/path/file') ];
238
239 # or we can read into a buffer:
240 my $buffer;
241 read_file('/path/file', buf_ref => \$buffer);
242
243 # or we can set the block size for the read
244 my $text_ref = read_file('/path/file', blk_size => 10_000_000, array_ref => 1);
245
246 # or we can get a scalar reference
247 my $text_ref = read_file('/path/file', scalar_ref => 1);
248
249 This function reads in an entire file and returns its contents to the
250 caller. In scalar context it returns the entire file as a single
251 scalar. In list context it will return a list of lines (using the
252 current value of $/ as the separator, including support for paragraph
253 mode when it is set to '').
254
255 The first argument is the path to the file to be slurped in.
256
257 The next argument(s) is either a hash reference or a flattened hash,
258 "key => value" pairs. The following options are available:
259
260 · array_ref
261
262 The "array_ref" option is a boolean option, defaulted to false (0).
263 Setting this option to true (1) will only have relevance if the
264 "read_file" function is called in scalar context. When true, the
265 "read_file" function will return a reference to an array of the
266 lines in the file.
267
268 · binmode
269
270 The "binmode" option is a string option, defaulted to empty ('').
271 If you set the "binmode" option, then its value is passed to a call
272 to "binmode" on the opened handle. You can use this to set the file
273 to be read in binary mode, utf8, etc. See "perldoc -f binmode" for
274 more.
275
276 · blk_size
277
278 You can use this option to set the block size used when slurping
279 from an already open handle (like "\*STDIN"). It defaults to 1MB.
280
281 · buf_ref
282
283 The "buf_ref" option can be used in conjunction with any of the
284 other options. You can use this option to pass in a scalar
285 reference and the slurped file contents will be stored in the
286 scalar. This saves an extra copy of the slurped file and can lower
287 RAM usage vs returning the file. It is usually the fastest way to
288 read a file into a scalar.
289
290 · chomp
291
292 The "chomp" option is a boolean option, defaulted to false (0).
293 Setting this option to true (1) will cause each line to have its
294 contents "chomp"ed. This option works in list context or in scalar
295 context with the "array_ref" option.
296
297 · err_mode
298
299 The "err_mode" option has three possible values: "quiet", "carp",
300 or the default, "croak". In "quiet" mode, all errors will be
301 silent. In "carp" mode, all errors will be emitted as warnings.
302 And, in "croak" mode, all errors will be emitted as exceptions.
303 Take a look at Try::Tiny or Syntax::Keyword::Try to see how to
304 catch exceptions.
305
306 · scalar_ref
307
308 The "scalar_ref" option is a boolean option, defaulted to false
309 (0). It only has meaning in scalar context. The return value will
310 be a scalar reference to a string which is the contents of the
311 slurped file. This will usually be faster than returning the plain
312 scalar. It will also save memory as it will not make a copy of the
313 file to return.
314
315 rf
316 use File::Spec qw(rf);
317 my $text = rf('/path/file');
318
319 The "rf" function is simply a synonym for the "read_file" in
320 File::Slurp function.
321
322 slurp
323 use File::Spec qw(slurp);
324 my $text = slurp('/path/file');
325
326 The "slurp" function is simply a synonym for the "read_file" in
327 File::Slurp function.
328
329 wf
330 use File::Spec qw(wf);
331 my $res = wf('/path/file', "Some text");
332
333 The "wf" function is simply a synonym for the "write_file" in
334 File::Slurp function.
335
336 write_file
337 use File::Slurp qw(write_file);
338 write_file('/path/file', @data);
339 write_file('/path/file', {append => 1}, @data);
340 write_file('/path/file', {binmode => ':raw'}, $buffer);
341 write_file('/path/file', \$buffer);
342 write_file('/path/file', $buffer);
343 write_file('/path/file', \@lines);
344 write_file('/path/file', @lines);
345
346 # binmode
347 write_file('/path/file', {binmode => ':raw'}, @data);
348 write_file('/path/file', {binmode => ':utf8'}, $utf_text);
349
350 # buffered
351 write_file('/path/file', {buf_ref => \$buffer});
352 write_file('/path/file', \$buffer);
353 write_file('/path/file', $buffer);
354
355 # append
356 write_file('/path/file', {append => 1}, @data);
357
358 # no clobbering
359 write_file('/path/file', {no_clobber => 1}, @data);
360
361 This function writes out an entire file in one call. By default
362 "write_file" returns 1 upon successfully writing the file or "undef" if
363 it encountered an error. You can change how errors are handled with the
364 "err_mode" option.
365
366 The first argument to "write_file" is the filename.
367
368 The next argument(s) is either a hash reference or a flattened hash,
369 "key => value" pairs. The following options are available:
370
371 · append
372
373 The "append" option is a boolean option, defaulted to false (0).
374 Setting this option to true (1) will cause the data to be be
375 written at the end of the current file. Internally this sets the
376 "sysopen" mode flag "O_APPEND".
377
378 The "append_file" in File::Slurp function sets this option by
379 default.
380
381 · atomic
382
383 The "atomic" option is a boolean option, defaulted to false (0).
384 Setting this option to true (1) will cause the file to be be
385 written to in an atomic fashion. A temporary file name is created
386 using "tempfile" in File::Temp. After the file is closed it is
387 renamed to the original file name (and "rename" is an atomic
388 operation on most OSes). If the program using this were to crash in
389 the middle of this, then the temporary file could be left behind.
390
391 · binmode
392
393 The "binmode" option is a string option, defaulted to empty ('').
394 If you set the "binmode" option, then its value is passed to a call
395 to "binmode" on the opened handle. You can use this to set the file
396 to be read in binary mode, utf8, etc. See "perldoc -f binmode" for
397 more.
398
399 · buf_ref
400
401 The "buf_ref" option is used to pass in a scalar reference which
402 has the data to be written. If this is set then any data arguments
403 (including the scalar reference shortcut) in @_ will be ignored.
404
405 · err_mode
406
407 The "err_mode" option has three possible values: "quiet", "carp",
408 or the default, "croak". In "quiet" mode, all errors will be
409 silent. In "carp" mode, all errors will be emitted as warnings.
410 And, in "croak" mode, all errors will be emitted as exceptions.
411 Take a look at Try::Tiny or Syntax::Keyword::Try to see how to
412 catch exceptions.
413
414 · no_clobber
415
416 The "no_clobber" option is a boolean option, defaulted to false
417 (0). Setting this option to true (1) will ensure an that existing
418 file will not be overwritten.
419
420 · perms
421
422 The "perms" option sets the permissions of newly-created files.
423 This value is modified by your process's "umask" and defaults to
424 0666 (same as "sysopen").
425
426 NOTE: this option is new as of File::Slurp version 9999.14.
427
429 These are exported by default or with
430
431 use File::Slurp qw(:std);
432 # read_file write_file overwrite_file append_file read_dir
433
434 These are exported with
435
436 use File::Slurp qw(:edit);
437 # edit_file edit_file_lines
438
439 You can get all subs in the module exported with
440
441 use File::Slurp qw(:all);
442
444 Uri Guttman, <uri@stemsystems.com>
445
447 Copyright (c) 2003 Uri Guttman. All rights reserved.
448
449 This program is free software; you can redistribute it and/or modify it
450 under the same terms as Perl itself.
451
452
453
454perl v5.30.0 2019-09-18 File::Slurp(3)