File::Slurp(3)
π File::Slurp π
okay so this is the File::Slurp(3) page from the User Contributed Perl Documentation, and it is literally about reading/writing whole files without making it a whole thing. bestie, it's giving βone call, whole file, no capβ β¨
πΈ NAME πΈ
File::Slurp β Simple and Efficient Reading/Writing/Modifying of Complete Files π
β¨ SYNOPSIS β¨
here's the vibe in code, bestie:
use File::Slurp;
# read in a whole file into a scalar
my $text = read_file('/path/file');
# read in a whole file into an array of lines
my @lines = read_file('/path/file');
# write out a whole file from a scalar
write_file('/path/file', $text);
# write out a whole file from an array of lines
write_file('/path/file', @lines);
# Here is a simple and fast way to load and save a simple config file
# made of key=value lines.
my %conf = read_file('/path/file') =~ /^(\w+)=(.*)$/mg;
write_file('/path/file', {atomic => 1}, map "$_=$conf{$_}\n", keys %conf);
# insert text at the beginning of a file
prepend_file('/path/file', $text);
# in-place edit to replace all 'foo' with 'bar' in file
edit_file { s/foo/bar/g } '/path/file';
# in-place edit to delete all lines with 'foo' from file
edit_file_lines sub { $_ = '' if /foo/ }, '/path/file';
# read in a whole directory of file names (skipping . and ..)
my @files = read_dir('/path/to/dir');
π« DESCRIPTION π«
okay so File::Slurp provides subs that let you read or write entire files with one simple call. They are designed to be simple to use, have flexible ways to pass in or get the file contents, and to be very efficient. There is also a sub to read in all the files in a directory. slay. π
π WARNING - PENDING DOOM π
okay bestie, technically you can, but do NOT use this module to work on file handles, pipes, sockets, standard IO, or the DATA handle. These are features implemented long ago that just really shouldn't be abused here. fr fr.
Be warned: this activity will lead to inaccurate encoding/decoding of data. π
All further mentions of actions on the above have been removed from this documentation and that feature set will likely be deprecated in the future. no cap.
In other words, if you don't have a filename to pass, consider using the standard do { local $/; <$fh> }, or Data::Section/Data::Section::Simple for working with __DATA__. π«Ά
π οΈ FUNCTIONS π οΈ
File::Slurp implements the following functions. okay so here's the whole cast, bestie:
π append_file π
use File::Slurp qw(append_file write_file);
my $res = append_file('/path/file', "Some text");
# same as
my $res = write_file('/path/file', {append => 1}, "Some text");
The append_file function is simply a synonym for the write_file in File::Slurp function, but ensures that the append option is set. that's it, that's the whole function π
π edit_file π
use File::Slurp qw(edit_file);
# perl -0777 -pi -e 's/foo/bar/g' /path/file
edit_file { s/foo/bar/g } '/path/file';
edit_file sub { s/foo/bar/g }, '/path/file';
sub replace_foo { s/foo/bar/g }
edit_file \&replace_foo, '/path/file';
The edit_file function reads in a file into $_, executes a code block that should modify $_, and then writes $_ back to the file. The edit_file function reads in the entire file and calls the code block one time. It is equivalent to the -pi command line options of Perl but you can call it from inside your program and not have to fork out a process. no fork, just vibes β¨
The first argument to edit_file is a code block or a code reference. The code block is not followed by a comma (as with grep and map) but a code reference is followed by a comma.
The next argument is the filename.
The next argument(s) is either a hash reference or a flattened hash, key => value pairs. The options are passed through to the write_file in File::Slurp function. All options are described there. Only the binmode and err_mode options are supported. The call to write_file in File::Slurp has the atomic option set so you will always have a consistent file. periodt.
π edit_file_lines π
use File::Slurp qw(edit_file_lines);
# perl -pi -e '$_ = "" if /foo/' /path/file
edit_file_lines { $_ = '' if /foo/ } '/path/file';
edit_file_lines sub { $_ = '' if /foo/ }, '/path/file';
sub delete_foo { $_ = '' if /foo/ }
edit_file \&delete_foo, '/path/file';
The edit_file_lines function reads each line of a file into $_, and executes a code block that should modify $_. It will then write $_ back to the file. It is equivalent to the -pi command line options of Perl but you can call it from inside your program and not have to fork out a process. π
The first argument to edit_file_lines is a code block or a code reference. The code block is not followed by a comma (as with grep and map) but a code reference is followed by a comma.
The next argument is the filename.
The next argument(s) is either a hash reference or a flattened hash, key => value pairs. The options are passed through to the write_file in File::Slurp function. All options are described there. Only the binmode and err_mode options are supported. The call to write_file in File::Slurp has the atomic option set so you will always have a consistent file. π
π ef π
use File::Slurp qw(ef);
# perl -0777 -pi -e 's/foo/bar/g' /path/file
ef { s/foo/bar/g } '/path/file';
ef sub { s/foo/bar/g }, '/path/file';
sub replace_foo { s/foo/bar/g }
ef \&replace_foo, '/path/file';
The ef function is simply a synonym for the edit_file in File::Slurp function. short king energy, love that for us π
π efl π
use File::Slurp qw(efl);
# perl -pi -e '$_ = "" if /foo/' /path/file
efl { $_ = '' if /foo/ } '/path/file';
efl sub { $_ = '' if /foo/ }, '/path/file';
sub delete_foo { $_ = '' if /foo/ }
efl \&delete_foo, '/path/file';
The efl function is simply a synonym for the edit_file_lines in File::Slurp function. iconic abbreviation behavior π
π overwrite_file π
use File::Slurp qw(overwrite_file);
my $res = overwrite_file('/path/file', "Some text");
The overwrite_file function is simply a synonym for the write_file in File::Slurp function. literally just a synonym, no extra drama π
π prepend_file π
use File::Slurp qw(prepend_file);
prepend_file('/path/file', $header);
prepend_file('/path/file', \@lines);
prepend_file('/path/file', { binmode => ':raw'}, $bin_data);
# equivalent to:
use File::Slurp qw(read_file write_file);
my $content = read_file('/path/file');
my $new_content = "hahahaha";
write_file('/path/file', $new_content . $content);
The prepend_file function is the opposite of append_file in File::Slurp as it writes new contents to the beginning of the file instead of the end. It is a combination of read_file in File::Slurp and write_file in File::Slurp. It works by first using read_file to slurp in the file and then calling write_file with the new data and the existing file data. π
The first argument to prepend_file is the filename.
The next argument(s) is either a hash reference or a flattened hash, key => value pairs. The options are passed through to the write_file in File::Slurp function. All options are described there.
Only the binmode and err_mode options are supported. The write_file call has the atomic option set so you will always have a consistent file. consistent file, no cap. β¨
π read_dir π
use File::Slurp qw(read_dir);
my @files = read_dir('/path/to/dir');
# all files, even the dots
my @files = read_dir('/path/to/dir', keep_dot_dot => 1);
# keep the full file path
my @paths = read_dir('/path/to/dir', prefix => 1);
# scalar context
my $files_ref = read_dir('/path/to/dir');
This function returns a list of the filenames in the supplied directory. In list context, an array is returned, in scalar context, an array reference is returned. bestie, context is literally everything π
The first argument is the path to the directory to read.
The next argument(s) is either a hash reference or a flattened hash, key => value pairs. The following options are available:
err_modeβ Theerr_modeoption has three possible values:quiet,carp, or the default,croak. Inquietmode, all errors will be silent. Incarpmode, all errors will be emitted as warnings. And, incroakmode, all errors will be emitted as exceptions. Take a look atTry::TinyorSyntax::Keyword::Tryto see how to catch exceptions. πkeep_dot_dotβ Thekeep_dot_dotoption is a boolean option, defaulted to false (0). Setting this option to true (1) will also return the.and..files that are removed from the file list by default. hi, dots πprefixβ Theprefixoption is a boolean option, defaulted to false (0). Setting this option to true (1) add the directory as a prefix to the file. The directory and the filename are joined usingFile::Spec->catfile()to ensure the proper directory separator is used for your OS. SeeFile::Spec. π
π read_file π
use File::Slurp qw(read_file);
my $text = read_file('/path/file');
my $bin = read_file('/path/file', { binmode => ':raw' });
my @lines = read_file('/path/file');
my $lines_ref = read_file('/path/file', array_ref => 1);
my $lines_ref = [ read_file('/path/file') ];
# or we can read into a buffer:
my $buffer;
read_file('/path/file', buf_ref => \$buffer);
# or we can set the block size for the read
my $text_ref = read_file('/path/file', blk_size => 10_000_000, array_ref => 1);
# or we can get a scalar reference
my $text_ref = read_file('/path/file', scalar_ref => 1);
This function reads in an entire file and returns its contents to the caller. In scalar context it returns the entire file as a single scalar. In list context it will return a list of lines (using the current value of $/ as the separator, including support for paragraph mode when it is set to ''). yes bestie, $/ is doing the lord's work π«Ά
The first argument is the path to the file to be slurped in.
The next argument(s) is either a hash reference or a flattened hash, key => value pairs. The following options are available:
array_refβ Thearray_refoption is a boolean option, defaulted to false (0). Setting this option to true (1) will only have relevance if theread_filefunction is called in scalar context. When true, theread_filefunction will return a reference to an array of the lines in the file. array ref realness πbinmodeβ Thebinmodeoption is a string option, defaulted to empty (''). If you set thebinmodeoption, then its value is passed to a call tobinmodeon the opened handle. You can use this to set the file to be read in binary mode, utf8, etc. Seeperldoc -f binmodefor more. encoding bestie says hi πblk_sizeβ okay so this one's description is literally waiting for you in part 2, bestie π«Άbufsizeβ bestie this one's for when you're slurping out of a handle that's already open (like\*STDIN). It sets the block size used for the read. Default is 1MB. Very demure, very mindful. β¨buf_refβ this one plays nice with literally any of the other options. Pass in a scalar reference and the slurped file contents get stored in that scalar. It saves an extra copy of the slurped file and can lower RAM usage vs. returning the file. Ngl it's usually the fastest way to read a file into a scalar. πchompβ boolean option, defaulted to false (0). Set it to true (1) and each line gets its contentschomped. Works in list context, or in scalar context with thearray_refoption.err_modeβ three possible values:quiet,carp, or the default,croak. Inquietmode, all errors will be silent. Incarpmode, all errors will be emitted as warnings. And incroakmode, all errors will be emitted as exceptions. Take a look at Try::Tiny or Syntax::Keyword::Try to see how to catch exceptions. π«Άscalar_refβ boolean, defaulted to false (0). It only has meaning in scalar context. The return value will be a scalar reference to a string which is the contents of the slurped file. This will usually be faster than returning the plain scalar. It will also save memory as it will not make a copy of the file to return. Efficiency is the vibe. π
π rf
use File::Slurp qw(rf);
my $text = rf('/path/file');
The rf function is simply a synonym for the read_file in File::Slurp function. Same girl, shorter name.
πΈ slurp
use File::Slurp qw(slurp);
my $text = slurp('/path/file');
The slurp function is simply a synonym for the read_file in File::Slurp function. It's giving alias energy, we love her.
π¦ wf
use File::Slurp qw(wf);
my $res = wf('/path/file', "Some text");
The wf function is simply a synonym for the write_file in File::Slurp function. Two letters, endlessly iconic.
π write_file
use File::Slurp qw(write_file);
write_file('/path/file', @data);
write_file('/path/file', {append => 1}, @data);
write_file('/path/file', {binmode => ':raw'}, $buffer);
write_file('/path/file', \$buffer);
write_file('/path/file', $buffer);
write_file('/path/file', \@lines);
write_file('/path/file', @lines);
# binmode
write_file('/path/file', {binmode => ':raw'}, @data);
write_file('/path/file', {binmode => ':utf8'}, $utf_text);
# buffered
write_file('/path/file', {buf_ref => \$buffer});
write_file('/path/file', \$buffer);
write_file('/path/file', $buffer);
# append
write_file('/path/file', {append => 1}, @data);
# no clobbering
write_file('/path/file', {no_clobber => 1}, @data);
This function writes out an entire file in one call. The whole file. One call. We're obsessed. π
By default write_file returns 1 upon successfully writing the file, or undef if it encountered an error. You can change how errors are handled with the err_mode option.
The first argument to write_file is the filename.
The next argument(s) is either a hash reference or a flattened hash, key => value pairs. The following options are available:
appendβ boolean, defaulted to false (0). Set it to true (1) and the data gets written at the end of the current file instead of steamrolling it. Internally this sets thesysopenmode flagO_APPEND. Theappend_filein File::Slurp function sets this option by default.atomicβ boolean, defaulted to false (0). Set it to true (1) and the file gets written in an atomic fashion. A temporary file name is created usingtempfilein File::Temp. After the file is closed it is renamed to the original file name (andrenameis an atomic operation on most OSes). β οΈ If the program using this were to crash in the middle of this, then the temporary file could be left behind. So like, bestie, note that.binmodeβ a string option, defaulted to empty (''). If you set thebinmodeoption, then its value is passed to a call tobinmodeon the opened handle. You can use this to set the file to be read in binary mode, utf8, etc. Seeperldoc -f binmodefor more.buf_refβ used to pass in a scalar reference which has the data to be written. If this is set then any data arguments (including the scalar reference shortcut) in@_will be ignored. She said don't talk to me, I have my buffer. πerr_modeβ three possible values:quiet,carp, or the default,croak. Inquietmode, all errors will be silent. Incarpmode, all errors will be emitted as warnings. And incroakmode, all errors will be emitted as exceptions. Take a look at Try::Tiny or Syntax::Keyword::Try to see how to catch exceptions. (Yes, same option, same three modes β consistency is a slay.)no_clobberβ boolean, defaulted to false (0). Set it to true (1) and it ensures that an existing file will not be overwritten. Protecting the og file's peace. π‘οΈpermsβ sets the permissions of newly-created files. This value is modified by your process'sumaskand defaults to 0666 (same assysopen).
NOTE: this option is new as of File::Slurp version 9999.14.
π EXPORT
These are exported by default or with:
use File::Slurp qw(:std);
# read_file write_file overwrite_file append_file read_dir
These are exported with:
use File::Slurp qw(:edit);
# edit_file edit_file_lines
You can get all subs in the module exported with:
use File::Slurp qw(:all);
β SEE ALSO
- File::Slurper β provides a straightforward set of functions for the most common tasks of reading/writing text and binary files. Lowkey the chill one.
- Path::Tiny β lightweight and comprehensive file handling, including simple methods for reading, writing, and editing text and binary files. She does it all.
- Mojo::File β similar to Path::Tiny for the Mojo toolkit, always works in bytes. Bytes only, no thoughts, head empty, iconic.
π AUTHOR
Uri Guttman, <uri@stemsystems.com>
π COPYRIGHT & LICENSE
Copyright (c) 2003 Uri Guttman. All rights reserved.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
and that's the whole page, bestie! π You just read File::Slurp(3), from perl v5.42.0, dated 2020-07-01 β go forth and slurp responsibly. β¨ππ¦
π¦ where this page comes from
- opensuse-leap 16.0: perl-File-Slurp 9999.32-160000.2.2 Β· Artistic-1.0 OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms