Commit 336e6624 authored by root's avatar root

fixed deprecated sysread() on utf8 handles

parent 0e7b2053
...@@ -162,7 +162,7 @@ ExtUtils::CBuilder 0.280205 ...@@ -162,7 +162,7 @@ ExtUtils::CBuilder 0.280205
File::Listing 6.04 File::Listing 6.04
File::Path 2.09|--notest|--force File::Path 2.09|--notest|--force
File::ShareDir 1.03 File::ShareDir 1.03
File::Slurp 9999.19 File::Slurp 9999.32
File::Spec::Native 1.003 File::Spec::Native 1.003
File::chdir 0.1008 File::chdir 0.1008
Filesys::Notify::Simple 0.08 Filesys::Notify::Simple 0.08
......
package File::Slurp; package File::Slurp;
use 5.6.2 ;
use strict; use strict;
use warnings ; use warnings ;
our $VERSION = '9999.32';
$VERSION = eval $VERSION;
use Carp ; use Carp ;
use Exporter ; use Exporter qw(import);
use Fcntl qw( :DEFAULT ) ; use Fcntl qw( :DEFAULT ) ;
use File::Basename ();
use File::Spec;
use File::Temp qw(tempfile);
use IO::Handle ();
use POSIX qw( :fcntl_h ) ; use POSIX qw( :fcntl_h ) ;
use Errno ; use Errno ;
#use Symbol ;
use vars qw( @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $VERSION ) ;
@ISA = qw( Exporter ) ;
$VERSION = '9999.19';
my @std_export = qw( my @std_export = qw(
read_file read_file
...@@ -25,268 +24,122 @@ my @std_export = qw( ...@@ -25,268 +24,122 @@ my @std_export = qw(
read_dir read_dir
) ; ) ;
my @edit_export = qw( my @edit_export = qw(
edit_file edit_file
edit_file_lines edit_file_lines
) ; ) ;
my @ok_export = qw( my @abbrev_export = qw(
rf
wf
ef
efl
) ; ) ;
@EXPORT_OK = ( our @EXPORT_OK = (
@edit_export, @edit_export,
@abbrev_export,
qw( qw(
slurp slurp
prepend_file prepend_file
), ),
) ; ) ;
%EXPORT_TAGS = ( our %EXPORT_TAGS = (
'all' => [ @std_export, @edit_export, @EXPORT_OK ], 'all' => [ @std_export, @edit_export, @abbrev_export, @EXPORT_OK ],
'edit' => [ @edit_export ], 'edit' => [ @edit_export ],
'std' => [ @std_export ], 'std' => [ @std_export ],
'abr' => [ @abbrev_export ],
) ; ) ;
@EXPORT = @std_export ; our @EXPORT = @std_export ;
my $max_fast_slurp_size = 1024 * 100 ; my $max_fast_slurp_size = 1024 * 100 ;
my $is_win32 = $^O =~ /win32/i ; my $is_win32 = $^O =~ /win32/i ;
# Install subs for various constants that aren't set in older perls
# (< 5.005). Fcntl on old perls uses Exporter to define subs without a
# () prototype These can't be overridden with the constant pragma or
# we get a prototype mismatch. Hence this less than aesthetically
# appealing BEGIN block:
BEGIN {
unless( defined &SEEK_SET ) {
*SEEK_SET = sub { 0 };
*SEEK_CUR = sub { 1 };
*SEEK_END = sub { 2 };
}
unless( defined &O_BINARY ) {
*O_BINARY = sub { 0 };
*O_RDONLY = sub { 0 };
*O_WRONLY = sub { 1 };
}
unless ( defined &O_APPEND ) {
if ( $^O =~ /olaris/ ) {
*O_APPEND = sub { 8 };
*O_CREAT = sub { 256 };
*O_EXCL = sub { 1024 };
}
elsif ( $^O =~ /inux/ ) {
*O_APPEND = sub { 1024 };
*O_CREAT = sub { 64 };
*O_EXCL = sub { 128 };
}
elsif ( $^O =~ /BSD/i ) {
*O_APPEND = sub { 8 };
*O_CREAT = sub { 512 };
*O_EXCL = sub { 2048 };
}
}
}
# print "OS [$^O]\n" ;
# print "O_BINARY = ", O_BINARY(), "\n" ;
# print "O_RDONLY = ", O_RDONLY(), "\n" ;
# print "O_WRONLY = ", O_WRONLY(), "\n" ;
# print "O_APPEND = ", O_APPEND(), "\n" ;
# print "O_CREAT ", O_CREAT(), "\n" ;
# print "O_EXCL ", O_EXCL(), "\n" ;
*slurp = \&read_file ; *slurp = \&read_file ;
*rf = \&read_file ;
sub read_file { sub read_file {
my $file_name = shift;
my $file_name = shift ; my $opts = (ref $_[0] eq 'HASH') ? shift : {@_};
my $opts = ( ref $_[0] eq 'HASH' ) ? shift : { @_ } ; # options we care about:
# array_ref binmode blk_size buf_ref chomp err_mode scalar_ref
# this is the optimized read_file for shorter files.
# the test for -s > 0 is to allow pseudo files to be read with the # let's see if we have a stringified object before doing anything else
# regular loop since they return a size of 0. # We then only have to deal with when we are given a file handle/globref
if (ref($file_name)) {
if ( !ref $file_name && -e $file_name && -s _ > 0 && my $ref_result = _check_ref($file_name, $opts);
-s _ < $max_fast_slurp_size && !%{$opts} && !wantarray ) { if (ref($ref_result)) {
@_ = ($opts, $ref_result);
goto &_error;
my $fh ;
unless( sysopen( $fh, $file_name, O_RDONLY ) ) {
@_ = ( $opts, "read_file '$file_name' - sysopen: $!");
goto &_error ;
} }
$file_name = $ref_result if $ref_result;
my $read_cnt = sysread( $fh, my $buf, -s _ ) ; # we have now stringified $file_name if possible. if it's still a ref
# then we probably have a file handle
unless ( defined $read_cnt ) {
@_ = ( $opts,
"read_file '$file_name' - small sysread: $!");
goto &_error ;
}
$buf =~ s/\015\012/\n/g if $is_win32 ;
return $buf ;
} }
# set the buffer to either the passed in one or ours and init it to the null my $fh;
# string if (ref($file_name)) {
$fh = $file_name;
my $buf ;
my $buf_ref = $opts->{'buf_ref'} || \$buf ;
${$buf_ref} = '' ;
my( $read_fh, $size_left, $blk_size ) ;
# deal with ref for a file name
# it could be an open handle or an overloaded object
if ( ref $file_name ) {
my $ref_result = _check_ref( $file_name ) ;
if ( ref $ref_result ) {
# we got an error, deal with it
@_ = ( $opts, $ref_result ) ;
goto &_error ;
}
if ( $ref_result ) {
# we got an overloaded object and the result is the stringified value
# use it as the file name
$file_name = $ref_result ;
}
else {
# here we have just an open handle. set $read_fh so we don't do a sysopen
$read_fh = $file_name ;
$blk_size = $opts->{'blk_size'} || 1024 * 1024 ;
$size_left = $blk_size ;
}
} }
else {
# see if we have a path we need to open # to keep with the old ways, read in :raw by default
unless (open $fh, "<:raw", $file_name) {
unless ( $read_fh ) { @_ = ($opts, "read_file '$file_name' - open: $!");
goto &_error;
# a regular file. set the sysopen mode
my $mode = O_RDONLY ;
#printf "RD: BINARY %x MODE %x\n", O_BINARY, $mode ;
$read_fh = local( *FH ) ;
# $read_fh = gensym ;
unless ( sysopen( $read_fh, $file_name, $mode ) ) {
@_ = ( $opts, "read_file '$file_name' - sysopen: $!");
goto &_error ;
}
if ( my $binmode = $opts->{'binmode'} ) {
binmode( $read_fh, $binmode ) ;
} }
# even though we set raw, let binmode take place here (busted)
# get the size of the file for use in the read loop if (my $bm = $opts->{binmode}) {
binmode $fh, $bm;
$size_left = -s $read_fh ;
#print "SIZE $size_left\n" ;
# we need a blk_size if the size is 0 so we can handle pseudofiles like in
# /proc. these show as 0 size but have data to be slurped.
unless( $size_left ) {
$blk_size = $opts->{'blk_size'} || 1024 * 1024 ;
$size_left = $blk_size ;
} }
} }
# infinite read loop. we exit when we are done slurping # we are now sure to have an open file handle. Let's slurp it in the same
# way that File::Slurper does.
while( 1 ) { my $buf;
my $buf_ref = $opts->{buf_ref} || \$buf;
# do the read and see how much we got ${$buf_ref} = '';
my $blk_size = $opts->{blk_size} || 1024 * 1024;
my $read_cnt = sysread( $read_fh, ${$buf_ref}, if (my $size = -f $fh && -s _) {
$size_left, length ${$buf_ref} ) ; $blk_size = $size if $size < $blk_size;
my ($pos, $read) = 0;
# since we're using sysread Perl won't automatically restart the call do {
# when interrupted by a signal. unless(defined($read = read $fh, ${$buf_ref}, $blk_size, $pos)) {
@_ = ($opts, "read_file '$file_name' - read: $!");
next if $!{EINTR}; goto &_error;
}
unless ( defined $read_cnt ) { $pos += $read;
} while ($read && $pos < $size);
@_ = ( $opts, "read_file '$file_name' - loop sysread: $!");
goto &_error ;
}
# good read. see if we hit EOF (nothing left to read)
last if $read_cnt == 0 ;
# loop if we are slurping a handle. we don't track $size_left then.
next if $blk_size ;
# count down how much we read and loop if we have more to read.
$size_left -= $read_cnt ;
last if $size_left <= 0 ;
} }
else {
# fix up cr/lf to be a newline if this is a windows text file ${$buf_ref} = do { local $/; <$fh> };
}
${$buf_ref} =~ s/\015\012/\n/g if $is_win32 && !$opts->{'binmode'} ; seek($fh, $opts->{_data_tell}, SEEK_SET) if $opts->{_is_data} && $opts->{_data_tell};
my $sep = $/ ; # line endings if we're on Windows
$sep = '\n\n+' if defined $sep && $sep eq '' ; ${$buf_ref} =~ s/\015\012/\012/g if ${$buf_ref} && $is_win32 && !$opts->{binmode};
# see if caller wants lines # we now have a buffer filled with the file content. Figure out how to
# return it to the user
if( wantarray || $opts->{'array_ref'} ) { my $want_array = wantarray; # let's only ask for this once
if ($want_array || $opts->{array_ref}) {
use re 'taint' ; use re 'taint';
my $sep = $/;
$sep = '\n\n+' if defined $sep && $sep eq '';
# split the buffered content into lines
my @lines = length(${$buf_ref}) ? my @lines = length(${$buf_ref}) ?
${$buf_ref} =~ /(.*?$sep|.+)/sg : () ; ${$buf_ref} =~ /(.*?$sep|.+)/sg : ();
chomp @lines if $opts->{chomp};
chomp @lines if $opts->{'chomp'} ; return \@lines if $opts->{array_ref};
return @lines;
# caller wants an array ref
return \@lines if $opts->{'array_ref'} ;
# caller wants list of lines
return @lines ;
} }
return $buf_ref if $opts->{scalar_ref};
# caller wants a scalar ref to the slurped text # if the function was called in scalar context, return the contents
return ${$buf_ref} if defined $want_array;
return $buf_ref if $opts->{'scalar_ref'} ; # if we were called in void context, return nothing
return;
# caller wants a scalar with the slurped text (normal scalar context)
return ${$buf_ref} if defined wantarray ;
# caller passed in an i/o buffer by reference (normal void context)
return ;
} }
# errors in this sub are returned as scalar refs # errors in this sub are returned as scalar refs
...@@ -295,7 +148,7 @@ sub read_file { ...@@ -295,7 +148,7 @@ sub read_file {
sub _check_ref { sub _check_ref {
my( $handle ) = @_ ; my( $handle, $opts ) = @_ ;
# check if we are reading from a handle (GLOB or IO object) # check if we are reading from a handle (GLOB or IO object)
...@@ -303,7 +156,7 @@ sub _check_ref { ...@@ -303,7 +156,7 @@ sub _check_ref {
# we have a handle. deal with seeking to it if it is DATA # we have a handle. deal with seeking to it if it is DATA
my $err = _seek_data_handle( $handle ) ; my $err = _seek_data_handle( $handle, $opts ) ;
# return the error string if any # return the error string if any
...@@ -328,7 +181,10 @@ sub _check_ref { ...@@ -328,7 +181,10 @@ sub _check_ref {
sub _seek_data_handle { sub _seek_data_handle {
my( $handle ) = @_ ; my( $handle, $opts ) = @_ ;
# store some meta-data about the __DATA__ file handle
$opts->{_is_data} = 0;
$opts->{_data_tell} = 0;
# DEEP DARK MAGIC. this checks the UNTAINT IO flag of a # DEEP DARK MAGIC. this checks the UNTAINT IO flag of a
# glob/handle. only the DATA handle is untainted (since it is from # glob/handle. only the DATA handle is untainted (since it is from
...@@ -350,11 +206,18 @@ ERR ...@@ -350,11 +206,18 @@ ERR
if ( B::svref_2object( $handle )->IO->IoFLAGS & 16 ) { if ( B::svref_2object( $handle )->IO->IoFLAGS & 16 ) {
# we now know we have the data handle. Let's store its original
# location in the file so that we can put it back after the read.
# this is only done for Bugwards-compatibility in some dists such as
# CPAN::Index::API that made use of the oddity where sysread was in use
# before
$opts->{_is_data} = 1;
$opts->{_data_tell} = tell($handle);
# set the seek position to the current tell. # set the seek position to the current tell.
unless( sysseek( $handle, tell( $handle ), SEEK_SET ) ) { # unless( sysseek( $handle, tell( $handle ), SEEK_SET ) ) {
return "read_file '$handle' - sysseek: $!" ; # return "read_file '$handle' - sysseek: $!" ;
} # }
} }
# seek was successful, return no error string # seek was successful, return no error string
...@@ -362,190 +225,118 @@ ERR ...@@ -362,190 +225,118 @@ ERR
return ; return ;
} }
*wf = \&write_file ;
sub write_file { sub write_file {
my $file_name = shift;
my $file_name = shift ; my $opts = (ref $_[0] eq 'HASH') ? shift : {};
# options we care about:
# get the optional argument hash ref from @_ or an empty hash ref. # append atomic binmode buf_ref err_mode no_clobber perms
my $opts = ( ref $_[0] eq 'HASH' ) ? shift : {} ; my $fh;
my $no_truncate = 0;
my( $buf_ref, $write_fh, $no_truncate, $orig_file_name, $data_is_ref ) ; my $orig_filename;
# let's see if we have a stringified object or some sort of handle
# get the buffer ref - it depends on how the data is passed into write_file # or globref before doing anything else
# after this if/else $buf_ref will have a scalar ref to the data. if (ref($file_name)) {
my $ref_result = _check_ref($file_name, $opts);
if ( ref $opts->{'buf_ref'} eq 'SCALAR' ) { if (ref($ref_result)) {
# some error happened while checking for a ref
# a scalar ref passed in %opts has the data @_ = ($opts, $ref_result);
# note that the data was passed by ref goto &_error;
$buf_ref = $opts->{'buf_ref'} ;
$data_is_ref = 1 ;
}
elsif ( ref $_[0] eq 'SCALAR' ) {
# the first value in @_ is the scalar ref to the data
# note that the data was passed by ref
$buf_ref = shift ;
$data_is_ref = 1 ;
}
elsif ( ref $_[0] eq 'ARRAY' ) {
# the first value in @_ is the array ref to the data so join it.
${$buf_ref} = join '', @{$_[0]} ;
}
else {
# good old @_ has all the data so join it.
${$buf_ref} = join '', @_ ;
}
# deal with ref for a file name
if ( ref $file_name ) {
my $ref_result = _check_ref( $file_name ) ;
if ( ref $ref_result ) {
# we got an error, deal with it
@_ = ( $opts, $ref_result ) ;
goto &_error ;
} }
if ($ref_result) {
if ( $ref_result ) { # we have now stringified $file_name from the overloaded obj
$file_name = $ref_result;
# we got an overloaded object and the result is the stringified value
# use it as the file name
$file_name = $ref_result ;
} }
else { else {
# we now have a proper handle ref
# we now have a proper handle ref. # make sure we don't call truncate on it
# make sure we don't call truncate on it. $fh = $file_name;
$no_truncate = 1;
$write_fh = $file_name ; # can't do atomic or permissions on a file handle
$no_truncate = 1 ; delete $opts->{atomic};
delete $opts->{perms};
} }
} }
# see if we have a path we need to open # open the file for writing if we were given a filename
unless ($fh) {
unless( $write_fh ) { $orig_filename = $file_name;
my $perms = defined($opts->{perms}) ? $opts->{perms} : 0666;
# spew to regular file. # set the mode for the sysopen
my $mode = O_WRONLY | O_CREAT;
if ( $opts->{'atomic'} ) { $mode |= O_APPEND if $opts->{append};
$mode |= O_EXCL if $opts->{no_clobber};
# in atomic mode, we spew to a temp file so make one and save the original if ($opts->{atomic}) {
# file name. # in an atomic write, we must open a new file in the same directory
$orig_file_name = $file_name ; # as the original to account for ACLs. We must also set the new file
$file_name .= ".$$" ; # to the same permissions as the original unless overridden by the
# caller's request to set a specified permission set.
my $dir = File::Spec->rel2abs(File::Basename::dirname($file_name));
if (!defined($opts->{perms}) && -e $file_name && -f _) {
$perms = 07777 & (stat $file_name)[2];
}
# we must ensure we're using a good temporary filename (doesn't already
# exist). This is slower, but safer.
{
local $^W = 0; # AYFKM
(undef, $file_name) = tempfile('.tempXXXXX', DIR => $dir, OPEN => 0);
}
} }
$fh = local *FH;
# set the mode for the sysopen unless (sysopen($fh, $file_name, $mode, $perms)) {
@_ = ($opts, "write_file '$file_name' - sysopen: $!");
my $mode = O_WRONLY | O_CREAT ; goto &_error;
$mode |= O_APPEND if $opts->{'append'} ;
$mode |= O_EXCL if $opts->{'no_clobber'} ;
my $perms = $opts->{perms} ;
$perms = 0666 unless defined $perms ;
#printf "WR: BINARY %x MODE %x\n", O_BINARY, $mode ;
# open the file and handle any error.
$write_fh = local( *FH ) ;
# $write_fh = gensym ;
unless ( sysopen( $write_fh, $file_name, $mode, $perms ) ) {
@_ = ( $opts, "write_file '$file_name' - sysopen: $!");
goto &_error ;
} }
} }
# we now have an open file handle as well as data to write to that handle
if ( my $binmode = $opts->{'binmode'} ) { if (my $binmode = $opts->{binmode}) {
binmode( $write_fh, $binmode ) ; binmode($fh, $binmode);
} }
sysseek( $write_fh, 0, SEEK_END ) if $opts->{'append'} ; # get the data to print to the file
# get the buffer ref - it depends on how the data is passed in
#print 'WR before data ', unpack( 'H*', ${$buf_ref}), "\n" ; # after this if/else $buf_ref will have a scalar ref to the data
my $buf_ref;
# fix up newline to write cr/lf if this is a windows text file my $data_is_ref = 0;
if (ref($opts->{buf_ref}) eq 'SCALAR') {
if ( $is_win32 && !$opts->{'binmode'} ) { # a scalar ref passed in %opts has the data
# note that the data was passed by ref
# copy the write data if it was passed by ref so we don't clobber the $buf_ref = $opts->{buf_ref};
# caller's data $data_is_ref = 1;
$buf_ref = \do{ my $copy = ${$buf_ref}; } if $data_is_ref ; }
${$buf_ref} =~ s/\n/\015\012/g ; elsif (ref($_[0]) eq 'SCALAR') {
# the first value in @_ is the scalar ref to the data
# note that the data was passed by ref
$buf_ref = shift;
$data_is_ref = 1;
}
elsif (ref($_[0]) eq 'ARRAY') {
# the first value in @_ is the array ref to the data so join it.
${$buf_ref} = join '', @{$_[0]};
}
else {
# good old @_ has all the data so join it.
${$buf_ref} = join '', @_;
} }
#print 'after data ', unpack( 'H*', ${$buf_ref}), "\n" ; # seek and print
seek($fh, 0, SEEK_END) if $opts->{append};
# get the size of how much we are writing and init the offset into that buffer print {$fh} ${$buf_ref};
truncate($fh, tell($fh)) unless $no_truncate;
my $size_left = length( ${$buf_ref} ) ; close($fh);
my $offset = 0 ;
# loop until we have no more data left to write
do {
# do the write and track how much we just wrote
my $write_cnt = syswrite( $write_fh, ${$buf_ref},
$size_left, $offset ) ;
# since we're using syswrite Perl won't automatically restart the call
# when interrupted by a signal.
next if $!{EINTR};
unless ( defined $write_cnt ) {
@_ = ( $opts, "write_file '$file_name' - syswrite: $!");
goto &_error ;
}
# track how much left to write and where to write from in the buffer
$size_left -= $write_cnt ;
$offset += $write_cnt ;
} while( $size_left > 0 ) ;
# we truncate regular files in case we overwrite a long file with a shorter file
# so seek to the current position to get it (same as tell()).
truncate( $write_fh,
sysseek( $write_fh, 0, SEEK_CUR ) ) unless $no_truncate ;
close( $write_fh ) ;
# handle the atomic mode - move the temp file to the original filename.
if ( $opts->{'atomic'} && !rename( $file_name, $orig_file_name ) ) {
@_ = ( $opts, "write_file '$file_name' - rename: $!" ) ; if ($opts->{atomic} && !rename($file_name, $orig_filename)) {
goto &_error ; @_ = ($opts, "write_file '$file_name' - rename: $!");
goto &_error;
} }
return 1 ; return 1;
} }
# this is for backwards compatibility with the previous File::Slurp module. # this is for backwards compatibility with the previous File::Slurp module.
# write_file always overwrites an existing file # write_file always overwrites an existing file
*overwrite_file = \&write_file ; *overwrite_file = \&write_file ;
# the current write_file has an append mode so we use that. this # the current write_file has an append mode so we use that. this
...@@ -631,6 +422,8 @@ sub prepend_file { ...@@ -631,6 +422,8 @@ sub prepend_file {
# edit a file as a scalar in $_ # edit a file as a scalar in $_
*ef = \&edit_file ;
sub edit_file(&$;$) { sub edit_file(&$;$) {
my( $edit_code, $file_name, $opts ) = @_ ; my( $edit_code, $file_name, $opts ) = @_ ;
...@@ -684,6 +477,8 @@ sub edit_file(&$;$) { ...@@ -684,6 +477,8 @@ sub edit_file(&$;$) {
return $write_result ; return $write_result ;
} }
*efl = \&edit_file_lines ;
sub edit_file_lines(&$;$) { sub edit_file_lines(&$;$) {
my( $edit_code, $file_name, $opts ) = @_ ; my( $edit_code, $file_name, $opts ) = @_ ;
...@@ -763,7 +558,7 @@ sub read_dir { ...@@ -763,7 +558,7 @@ sub read_dir {
if ( $opts->{'prefix'} ) { if ( $opts->{'prefix'} ) {
substr( $_, 0, 0, "$dir/" ) for @dir_entries ; $_ = File::Spec->catfile($dir, $_) for @dir_entries;
} }
return @dir_entries if wantarray ; return @dir_entries if wantarray ;
...@@ -818,444 +613,516 @@ File::Slurp - Simple and Efficient Reading/Writing/Modifying of Complete Files ...@@ -818,444 +613,516 @@ File::Slurp - Simple and Efficient Reading/Writing/Modifying of Complete Files
use File::Slurp; use File::Slurp;
# read in a whole file into a scalar # read in a whole file into a scalar
my $text = read_file( 'filename' ) ; my $text = read_file('/path/file');
# read in a whole file into an array of lines # read in a whole file into an array of lines
my @lines = read_file( 'filename' ) ; my @lines = read_file('/path/file');
# write out a whole file from a scalar # write out a whole file from a scalar
write_file( 'filename', $text ) ; write_file('/path/file', $text);
# write out a whole file from an array of lines # write out a whole file from an array of lines
write_file( 'filename', @lines ) ; write_file('/path/file', @lines);
# Here is a simple and fast way to load and save a simple config file # Here is a simple and fast way to load and save a simple config file
# made of key=value lines. # made of key=value lines.
my %conf = read_file( $file_name ) =~ /^(\w+)=(.*)$/mg ; my %conf = read_file('/path/file') =~ /^(\w+)=(.*)$/mg;
write_file( $file_name, {atomic => 1}, map "$_=$conf{$_}\n", keys %conf ) ; write_file('/path/file', {atomic => 1}, map "$_=$conf{$_}\n", keys %conf);
# insert text at the beginning of a file # insert text at the beginning of a file
prepend_file( 'filename', $text ) ; prepend_file('/path/file', $text);
# in-place edit to replace all 'foo' with 'bar' in file # in-place edit to replace all 'foo' with 'bar' in file
edit_file { s/foo/bar/g } 'filename' ; edit_file { s/foo/bar/g } '/path/file';
# in-place edit to delete all lines with 'foo' from file # in-place edit to delete all lines with 'foo' from file
edit_file_lines sub { $_ = '' if /foo/ }, 'filename' ; edit_file_lines sub { $_ = '' if /foo/ }, '/path/file';
# read in a whole directory of file names (skipping . and ..) # read in a whole directory of file names (skipping . and ..)
my @files = read_dir( '/path/to/dir' ) ; my @files = read_dir('/path/to/dir');
=head1 DESCRIPTION =head1 DESCRIPTION
This module provides subs that allow you to read or write entire files This module provides subs that allow you to read or write entire files
with one simple call. They are designed to be simple to use, have 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 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 efficient. There is also a sub to read in all the files in a
directory other than C<.> and C<..> directory.
These slurp/spew subs work for files, pipes and sockets, stdio, =head2 WARNING - PENDING DOOM
pseudo-files, and the DATA handle. Read more about why slurping files is
a good thing in the file 'slurp_article.pod' in the extras/ directory.
If you are interested in how fast these calls work, check out the Although you technically I<can>, do NOT use this module to work on file handles,
slurp_bench.pl program in the extras/ directory. It compares many pipes, sockets, standard IO, or the C<DATA> handle. These are
different forms of slurping. You can select the I/O direction, context features implemented long ago that just really shouldn't be abused here.
and file sizes. Use the --help option to see how to run it.
=head2 B<read_file> Be warned: this activity will lead to inaccurate encoding/decoding of data.
This sub reads in an entire file and returns its contents to the All further mentions of actions on the above have been removed from this
caller. In scalar context it returns the entire file as a single documentation and that feature set will likely be deprecated in the future.
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 '').
my $text = read_file( 'filename' ) ; In other words, if you don't have a filename to pass, consider using the
my $bin = read_file( 'filename' { binmode => ':raw' } ) ; standard C<< do { local $/; <$fh> } >>, or
my @lines = read_file( 'filename' ) ; L<Data::Section>/L<Data::Section::Simple> for working with C<__DATA__>.
my $lines = read_file( 'filename', array_ref => 1 ) ;
The first argument is the file to slurp in. If the next argument is a =head1 FUNCTIONS
hash reference, then it is used as the options. Otherwise the rest of
the argument list are is used as key/value options.
If the file argument is a handle (if it is a ref and is an IO or GLOB L<File::Slurp> implements the following functions.
object), then that handle is slurped in. This mode is supported so you
slurp handles such as C<DATA> and C<STDIN>. See the test handle.t for
an example that does C<open( '-|' )> and the child process spews data
to the parant which slurps it in. All of the options that control how
the data is returned to the caller still work in this case.
If the first argument is an overloaded object then its stringified value =head2 append_file
is used for the filename and that file is opened. This is a new feature
in 9999.14. See the stringify.t test for an example.
By default C<read_file> returns an undef in scalar contex or a single use File::Slurp qw(append_file write_file);
undef in list context if it encounters an error. Those are both my $res = append_file('/path/file', "Some text");
impossible to get with a clean read_file call which means you can check # same as
the return value and always know if you had an error. You can change how my $res = write_file('/path/file', {append => 1}, "Some text");
errors are handled with the C<err_mode> option.
Speed Note: If you call read_file and just get a scalar return value The C<append_file> function is simply a synonym for the
it is now optimized to handle shorter files. This is only used if no L<File::Slurp/"write_file"> function, but ensures that the C<append> option is
options are used, the file is shorter then 100k bytes, the filename is set.
a plain scalar and a scalar file is returned. If you want the fastest
slurping, use the C<buf_ref> or C<scalar_ref> options (see below)
NOTE: as of version 9999.06, read_file works correctly on the C<DATA> =head2 edit_file
handle. It used to need a sysseek workaround but that is now handled
when needed by the module itself.
You can optionally request that C<slurp()> is exported to your code. This use File::Slurp qw(edit_file);
is an alias for read_file and is meant to be forward compatible with # perl -0777 -pi -e 's/foo/bar/g' /path/file
Perl 6 (which will have slurp() built-in). 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 options for C<read_file> are: The C<edit_file> function reads in a file into C<$_>, executes a code block that
should modify C<$_>, and then writes C<$_> back to the file. The C<edit_file>
function reads in the entire file and calls the code block one time. It is
equivalent to the C<-pi> command line options of Perl but you can call it from
inside your program and not have to fork out a process.
=head3 binmode The first argument to C<edit_file> is a code block or a code reference. The
code block is not followed by a comma (as with C<grep> and C<map>) but a code
reference is followed by a comma.
If you set the binmode option, then its value is passed to a call to The next argument is the filename.
binmode on the opened handle. You can use this to set the file to be
read in binary mode, utf8, etc. See perldoc -f binmode for more.
my $bin_data = read_file( $bin_file, binmode => ':raw' ) ; The next argument(s) is either a hash reference or a flattened hash,
my $utf_text = read_file( $bin_file, binmode => ':utf8' ) ; C<< key => value >> pairs. The options are passed through to the
L<File::Slurp/"write_file"> function. All options are described there.
Only the C<binmode> and C<err_mode> options are supported. The call to
L<File::Slurp/"write_file"> has the C<atomic> option set so you will always
have a consistent file.
=head3 array_ref =head2 edit_file_lines
If this boolean option is set, the return value (only in scalar use File::Slurp qw(edit_file_lines);
context) will be an array reference which contains the lines of the # perl -pi -e '$_ = "" if /foo/' /path/file
slurped file. The following two calls are equivalent: 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';
my $lines_ref = read_file( $bin_file, array_ref => 1 ) ; The C<edit_file_lines> function reads each line of a file into C<$_>, and
my $lines_ref = [ read_file( $bin_file ) ] ; executes a code block that should modify C<$_>. It will then write C<$_> back
to the file. It is equivalent to the C<-pi> command line options of Perl but
you can call it from inside your program and not have to fork out a process.
=head3 chomp The first argument to C<edit_file_lines> is a code block or a code reference.
The code block is not followed by a comma (as with C<grep> and C<map>) but a
code reference is followed by a comma.
If this boolean option is set, the lines are chomped. This only The next argument is the filename.
happens if you are slurping in a list context or using the
C<array_ref> option.
=head3 scalar_ref The next argument(s) is either a hash reference or a flattened hash,
C<< key => value >> pairs. The options are passed through to the
L<File::Slurp/"write_file"> function. All options are described there.
Only the C<binmode> and C<err_mode> options are supported. The call to
L<File::Slurp/"write_file"> has the C<atomic> option set so you will always
have a consistent file.
If this boolean option is set, the return value (only in scalar =head2 ef
context) will be an 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. Run the extras/slurp_bench.pl script to see speed
comparisons.
my $text_ref = read_file( $bin_file, scalar_ref => 1 ) ; 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';
=head3 buf_ref The C<ef> function is simply a synonym for the L<File::Slurp/"edit_file">
function.
You can use this option to pass in a scalar reference and the slurped =head2 efl
file contents will be stored in the scalar. This can be used in
conjunction with any of the other options. This saves an extra copy of
the slurped file and can lower ram usage vs returning the file. It is
usually the fastest way to read a file into a scalar. Run the
extras/slurp_bench.pl script to see speed comparisons.
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';
read_file( $bin_file, buf_ref => \$buffer ) ; The C<efl> function is simply a synonym for the L<File::Slurp/"edit_file_lines">
function.
=head3 blk_size =head2 overwrite_file
You can use this option to set the block size used when slurping from use File::Slurp qw(overwrite_file);
an already open handle (like \*STDIN). It defaults to 1MB. my $res = overwrite_file('/path/file', "Some text");
my $text_ref = read_file( $bin_file, blk_size => 10_000_000, The C<overwrite_file> function is simply a synonym for the
array_ref => 1 ) ; L<File::Slurp/"write_file"> function.
=head3 err_mode =head2 prepend_file
You can use this option to control how read_file behaves when an error use File::Slurp qw(prepend_file);
occurs. This option defaults to 'croak'. You can set it to 'carp' or to prepend_file('/path/file', $header);
'quiet to have no special error handling. This code wants to carp and prepend_file('/path/file', \@lines);
then read another file if it fails. prepend_file('/path/file', { binmode => ':raw'}, $bin_data);
my $text_ref = read_file( $file, err_mode => 'carp' ) ; # equivalent to:
unless ( $text_ref ) { 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);
# read a different file but croak if not found The C<prepend_file> function is the opposite of L<File::Slurp/"append_file"> as
$text_ref = read_file( $another_file ) ; it writes new contents to the beginning of the file instead of the end. It is a
} combination of L<File::Slurp/"read_file"> and L<File::Slurp/"write_file">. It
works by first using C<read_file> to slurp in the file and then calling
# process ${$text_ref} C<write_file> with the new data and the existing file data.
=head2 B<write_file> The first argument to C<prepend_file> is the filename.
This sub writes out an entire file in one call. The next argument(s) is either a hash reference or a flattened hash,
C<< key => value >> pairs. The options are passed through to the
L<File::Slurp/"write_file"> function. All options are described there.
write_file( 'filename', @data ) ; Only the C<binmode> and C<err_mode> options are supported. The
C<write_file> call has the C<atomic> option set so you will always have
a consistent file.
The first argument to C<write_file> is the filename. The next argument =head2 read_dir
is an optional hash reference and it contains key/values that can
modify the behavior of C<write_file>. The rest of the argument list is
the data to be written to the file.
write_file( 'filename', {append => 1 }, @data ) ; use File::Slurp qw(read_dir);
write_file( 'filename', {binmode => ':raw'}, $buffer ) ; 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');
As a shortcut if the first data argument is a scalar or array reference, This function returns a list of the filenames in the supplied directory. In
it is used as the only data to be written to the file. Any following list context, an array is returned, in scalar context, an array reference is
arguments in @_ are ignored. This is a faster way to pass in the output returned.
to be written to the file and is equivalent to the C<buf_ref> option of
C<read_file>. These following pairs are equivalent but the pass by
reference call will be faster in most cases (especially with larger
files).
write_file( 'filename', \$buffer ) ; The first argument is the path to the directory to read.
write_file( 'filename', $buffer ) ;
write_file( 'filename', \@lines ) ; The next argument(s) is either a hash reference or a flattened hash,
write_file( 'filename', @lines ) ; C<< key => value >> pairs. The following options are available:
If the first argument is a handle (if it is a ref and is an IO or GLOB =over
object), then that handle is written to. This mode is supported so you
spew to handles such as \*STDOUT. See the test handle.t for an example
that does C<open( '-|' )> and child process spews data to the parent
which slurps it in. All of the options that control how the data are
passed into C<write_file> still work in this case.
If the first argument is an overloaded object then its stringified value =item
is used for the filename and that file is opened. This is new feature
in 9999.14. See the stringify.t test for an example.
By default C<write_file> returns 1 upon successfully writing the file or err_mode
undef if it encountered an error. You can change how errors are handled
with the C<err_mode> option.
The options are: The C<err_mode> option has three possible values: C<quiet>, C<carp>, or the
default, C<croak>. In C<quiet> mode, all errors will be silent. In C<carp> mode,
all errors will be emitted as warnings. And, in C<croak> mode, all errors will
be emitted as exceptions. Take a look at L<Try::Tiny> or
L<Syntax::Keyword::Try> to see how to catch exceptions.
=head3 binmode =item
If you set the binmode option, then its value is passed to a call to keep_dot_dot
binmode on the opened handle. You can use this to set the file to be
read in binary mode, utf8, etc. See perldoc -f binmode for more.
write_file( $bin_file, {binmode => ':raw'}, @data ) ; The C<keep_dot_dot> option is a boolean option, defaulted to false (C<0>).
write_file( $bin_file, {binmode => ':utf8'}, $utf_text ) ; Setting this option to true (C<1>) will also return the C<.> and C<..> files
that are removed from the file list by default.
=head3 perms =item
The perms option sets the permissions of newly-created files. This value prefix
is modified by your process's umask and defaults to 0666 (same as
sysopen).
NOTE: this option is new as of File::Slurp version 9999.14; The C<prefix> option is a boolean option, defaulted to false (C<0>).
Setting this option to true (C<1>) add the directory as a prefix to the file.
The directory and the filename are joined using C<< File::Spec->catfile() >> to
ensure the proper directory separator is used for your OS. See L<File::Spec>.
=head3 buf_ref =back
You can use this option to pass in a scalar reference which has the =head2 read_file
data to be written. If this is set then any data arguments (including
the scalar reference shortcut) in @_ will be ignored. These are
equivalent:
write_file( $bin_file, { buf_ref => \$buffer } ) ; use File::Slurp qw(read_file);
write_file( $bin_file, \$buffer ) ; my $text = read_file('/path/file');
write_file( $bin_file, $buffer ) ; 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') ];
=head3 atomic # or we can read into a buffer:
my $buffer;
read_file('/path/file', buf_ref => \$buffer);
If you set this boolean option, the file will be written to in an # or we can set the block size for the read
atomic fashion. A temporary file name is created by appending the pid my $text_ref = read_file('/path/file', blk_size => 10_000_000, array_ref => 1);
($$) to the file name argument and that file is spewed to. After the
file is closed it is renamed to the original file name (and rename is
an atomic operation on most OS's). If the program using this were to
crash in the middle of this, then the file with the pid suffix could
be left behind.
=head3 append # or we can get a scalar reference
my $text_ref = read_file('/path/file', scalar_ref => 1);
If you set this boolean option, the data will be written at the end of This function reads in an entire file and returns its contents to the
the current file. Internally this sets the sysopen mode flag O_APPEND. 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 C<$/> as the separator, including support for paragraph
mode when it is set to C<''>).
write_file( $file, {append => 1}, @data ) ; The first argument is the path to the file to be slurped in.
You The next argument(s) is either a hash reference or a flattened hash,
can import append_file and it does the same thing. C<< key => value >> pairs. The following options are available:
=head3 no_clobber =over
If you set this boolean option, an existing file will not be overwritten. =item
write_file( $file, {no_clobber => 1}, @data ) ; array_ref
=head3 err_mode The C<array_ref> option is a boolean option, defaulted to false (C<0>). Setting
this option to true (C<1>) will only have relevance if the C<read_file> function
is called in scalar context. When true, the C<read_file> function will return
a reference to an array of the lines in the file.
You can use this option to control how C<write_file> behaves when an =item
error occurs. This option defaults to 'croak'. You can set it to
'carp' or to 'quiet' to have no error handling other than the return
value. If the first call to C<write_file> fails it will carp and then
write to another file. If the second call to C<write_file> fails, it
will croak.
unless ( write_file( $file, { err_mode => 'carp', \$data ) ; binmode
# write a different file but croak if not found The C<binmode> option is a string option, defaulted to empty (C<''>). If you
write_file( $other_file, \$data ) ; set the C<binmode> option, then its value is passed to a call to C<binmode> on
} the opened handle. You can use this to set the file to be read in binary mode,
utf8, etc. See C<perldoc -f binmode> for more.
=head2 overwrite_file =item
This sub is just a typeglob alias to write_file since write_file blk_size
always overwrites an existing file. This sub is supported for
backwards compatibility with the original version of this module. See
write_file for its API and behavior.
=head2 append_file You can use this option to set the block size used when slurping from
an already open handle (like C<\*STDIN>). It defaults to 1MB.
=item
This sub will write its data to the end of the file. It is a wrapper buf_ref
around write_file and it has the same API so see that for the full
documentation. These calls are equivalent:
append_file( $file, @data ) ; The C<buf_ref> option can be used in conjunction with any of the other options.
write_file( $file, {append => 1}, @data ) ; You can use this option to pass in a scalar reference and the slurped
file contents will be stored in the scalar. This saves an extra copy of
the slurped file and can lower RAM usage vs returning the file. It is
usually the fastest way to read a file into a scalar.
=item
=head2 prepend_file chomp
This sub writes data to the beginning of a file. The previously existing The C<chomp> option is a boolean option, defaulted to false (C<0>). Setting
data is written after that so the effect is prepending data in front of this option to true (C<1>) will cause each line to have its contents C<chomp>ed.
a file. It is a counterpart to the append_file sub in this module. It This option works in list context or in scalar context with the C<array_ref>
works by first using C<read_file> to slurp in the file and then calling option.
C<write_file> with the new data and the existing file data.
The first argument to C<prepend_file> is the filename. The next argument =item
is an optional hash reference and it contains key/values that can modify
the behavior of C<prepend_file>. The rest of the argument list is the
data to be written to the file and that is passed to C<write_file> as is
(see that for allowed data).
Only the C<binmode> and C<err_mode> options are supported. The err_mode
C<write_file> call has the C<atomic> option set so you will always have
a consistant file. See above for more about those options.
C<prepend_file> is not exported by default, you need to import it The C<err_mode> option has three possible values: C<quiet>, C<carp>, or the
explicitly. default, C<croak>. In C<quiet> mode, all errors will be silent. In C<carp> mode,
all errors will be emitted as warnings. And, in C<croak> mode, all errors will
be emitted as exceptions. Take a look at L<Try::Tiny> or
L<Syntax::Keyword::Try> to see how to catch exceptions.
use File::Slurp qw( prepend_file ) ; =item
prepend_file( $file, $header ) ;
prepend_file( $file, \@lines ) ;
prepend_file( $file, { binmode => 'raw:'}, $bin_data ) ;
scalar_ref
=head2 edit_file, edit_file_lines The C<scalar_ref> option is a boolean option, defaulted to false (C<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.
These subs read in a file into $_, execute a code block which should =back
modify $_ and then write $_ back to the file. The difference between
them is that C<edit_file> reads the whole file into $_ and calls the
code block one time. With C<edit_file_lines> each line is read into $_
and the code is called for each line. In both cases the code should
modify $_ if desired and it will be written back out. These subs are
the equivalent of the -pi command line options of Perl but you can
call them from inside your program and not fork out a process. They
are in @EXPORT_OK so you need to request them to be imported on the
use line or you can import both of them with:
use File::Slurp qw( :edit ) ; =head2 rf
The first argument to C<edit_file> and C<edit_file_lines> is a code use File::Slurp qw(rf);
block or a code reference. The code block is not followed by a comma my $text = rf('/path/file');
(as with grep and map) but a code reference is followed by a
comma. See the examples below for both styles. The next argument is
the filename. The last argument is an optional hash reference and it
contains key/values that can modify the behavior of
C<prepend_file>.
Only the C<binmode> and C<err_mode> options are supported. The The C<rf> function is simply a synonym for the L<File::Slurp/"read_file">
C<write_file> call has the C<atomic> option set so you will always function.
have a consistant file. See above for more about those options.
Each group of calls below show a Perl command line instance and the =head2 slurp
equivalent calls to C<edit_file> and C<edit_file_lines>.
perl -0777 -pi -e 's/foo/bar/g' filename use File::Slurp qw(slurp);
use File::Slurp qw( edit_file ) ; my $text = slurp('/path/file');
edit_file { s/foo/bar/g } 'filename' ;
edit_file sub { s/foo/bar/g }, 'filename' ;
edit_file \&replace_foo, 'filename' ;
sub replace_foo { s/foo/bar/g }
perl -pi -e '$_ = "" if /foo/' filename The C<slurp> function is simply a synonym for the L<File::Slurp/"read_file">
use File::Slurp qw( edit_file_lines ) ; function.
use File::Slurp ;
edit_file_lines { $_ = '' if /foo/ } 'filename' ;
edit_file_lines sub { $_ = '' if /foo/ }, 'filename' ;
edit_file \&delete_foo, 'filename' ;
sub delete_foo { $_ = '' if /foo/ }
=head2 read_dir =head2 wf
use File::Slurp qw(wf);
my $res = wf('/path/file', "Some text");
The C<wf> function is simply a synonym for the
L<File::Slurp/"write_file"> function.
=head2 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);
This sub reads all the file names from directory and returns them to # binmode
the caller but C<.> and C<..> are removed by default. write_file('/path/file', {binmode => ':raw'}, @data);
write_file('/path/file', {binmode => ':utf8'}, $utf_text);
my @files = read_dir( '/path/to/dir' ) ; # buffered
write_file('/path/file', {buf_ref => \$buffer});
write_file('/path/file', \$buffer);
write_file('/path/file', $buffer);
The first argument is the path to the directory to read. If the next # append
argument is a hash reference, then it is used as the options. write_file('/path/file', {append => 1}, @data);
Otherwise the rest of the argument list are is used as key/value
options.
In list context C<read_dir> returns a list of the entries in the # no clobbering
directory. In a scalar context it returns an array reference which has write_file('/path/file', {no_clobber => 1}, @data);
the entries.
=head3 err_mode This function writes out an entire file in one call. By default C<write_file>
returns C<1> upon successfully writing the file or C<undef> if it encountered
an error. You can change how errors are handled with the C<err_mode> option.
If the C<err_mode> option is set, it selects how errors are handled (see The first argument to C<write_file> is the filename.
C<err_mode> in C<read_file> or C<write_file>).
=head3 keep_dot_dot The next argument(s) is either a hash reference or a flattened hash,
C<< key => value >> pairs. The following options are available:
If this boolean option is set, C<.> and C<..> are not removed from the =over
list of files.
my @all_files = read_dir( '/path/to/dir', keep_dot_dot => 1 ) ; =item
=head3 prefix append
If this boolean option is set, the string "$dir/" is prefixed to each The C<append> option is a boolean option, defaulted to false (C<0>). Setting
dir entry. This means you can directly use the results to open this option to true (C<1>) will cause the data to be be written at the end of
files. A common newbie mistake is not putting the directory in front the current file. Internally this sets the C<sysopen> mode flag C<O_APPEND>.
of entries when opening themn.
my @paths = read_dir( '/path/to/dir', prefix => 1 ) ; The L<File::Slurp/"append_file"> function sets this option by default.
=head2 EXPORT =item
These are exported by default or with atomic
use File::Slurp qw( :std ) ;
read_file write_file overwrite_file append_file read_dir The C<atomic> option is a boolean option, defaulted to false (C<0>). Setting
this option to true (C<1>) will cause the file to be be written to in an
atomic fashion. A temporary file name is created using L<File::Temp/"tempfile">.
After the file is closed it is renamed to the original file name
(and C<rename> is 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.
=item
binmode
The C<binmode> option is a string option, defaulted to empty (C<''>). If you
set the C<binmode> option, then its value is passed to a call to C<binmode> on
the opened handle. You can use this to set the file to be read in binary mode,
utf8, etc. See C<perldoc -f binmode> for more.
=item
buf_ref
The C<buf_ref> option is 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 C<@_> will be ignored.
=item
err_mode
The C<err_mode> option has three possible values: C<quiet>, C<carp>, or the
default, C<croak>. In C<quiet> mode, all errors will be silent. In C<carp> mode,
all errors will be emitted as warnings. And, in C<croak> mode, all errors will
be emitted as exceptions. Take a look at L<Try::Tiny> or
L<Syntax::Keyword::Try> to see how to catch exceptions.
=item
no_clobber
The C<no_clobber> option is a boolean option, defaulted to false (C<0>). Setting
this option to true (C<1>) will ensure an that existing file will not be
overwritten.
These are exported with =item
use File::Slurp qw( :edit ) ;
edit_file edit_file_lines perms
You can get all subs in the module exported with The C<perms> option sets the permissions of newly-created files. This value
use File::Slurp qw( :all ) ; is modified by your process's C<umask> and defaults to C<0666> (same as
C<sysopen>).
=head2 LICENSE NOTE: this option is new as of File::Slurp version 9999.14.
Same as Perl. =back
=head2 SEE ALSO =head1 EXPORT
An article on file slurping in extras/slurp_article.pod. There is These are exported by default or with
also a benchmarking script in extras/slurp_bench.pl.
=head2 BUGS use File::Slurp qw(:std);
# read_file write_file overwrite_file append_file read_dir
If run under Perl 5.004, slurping from the DATA handle will fail as These are exported with
that requires B.pm which didn't get into core until 5.005.
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);
=head1 SEE ALSO
=over
=item *
L<File::Slurper> - Provides a straightforward set of functions for the most
common tasks of reading/writing text and binary files.
=item *
L<Path::Tiny> - Lightweight and comprehensive file handling, including simple
methods for reading, writing, and editing text and binary files.
=item *
L<Mojo::File> - Similar to Path::Tiny for the L<Mojo> toolkit, always works in
bytes.
=back
=head1 AUTHOR =head1 AUTHOR
Uri Guttman, E<lt>uri AT stemsystems DOT comE<gt> Uri Guttman, <F<uri@stemsystems.com>>
=head1 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.
=cut =cut
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment