Authen-Quiz
view release on metacpan or search on metacpan
inc/File/Slurp.pm view on Meta::CPAN
# do the write and track how much we just wrote
my $write_cnt = syswrite( $write_fh, ${$buf_ref},
$size_left, $offset ) ;
unless ( defined $write_cnt ) {
# the write failed
@_ = ( $args, "write_file '$file_name' - syswrite: $!");
goto &_error ;
}
# track 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.
rename( $file_name, $orig_file_name ) if $args->{'atomic'} ;
return 1 ;
}
# this is for backwards compatibility with the previous File::Slurp module.
# write_file always overwrites an existing file
*overwrite_file = \&write_file ;
# the current write_file has an append mode so we use that. this
# supports the same API with an optional second argument which is a
# hash ref of options.
sub append_file {
# get the optional args hash ref
my $args = $_[1] ;
if ( ref $args eq 'HASH' ) {
# we were passed an args ref so just mark the append mode
$args->{append} = 1 ;
}
else {
# no args hash so insert one with the append mode
splice( @_, 1, 0, { append => 1 } ) ;
}
# magic goto the main write_file sub. this overlays the sub without touching
# the stack or @_
goto &write_file
}
# basic wrapper around opendir/readdir
sub read_dir {
my ($dir, %args ) = @_;
# this handle will be destroyed upon return
local(*DIRH);
# open the dir and handle any errors
unless ( opendir( DIRH, $dir ) ) {
@_ = ( \%args, "read_dir '$dir' - opendir: $!" ) ;
goto &_error ;
}
my @dir_entries = readdir(DIRH) ;
@dir_entries = grep( $_ ne "." && $_ ne "..", @dir_entries )
unless $args{'keep_dot_dot'} ;
return @dir_entries if wantarray ;
return \@dir_entries ;
}
# error handling section
#
# all the error handling uses magic goto so the caller will get the
# error message as if from their code and not this module. if we just
# did a call on the error code, the carp/croak would report it from
# this module since the error sub is one level down on the call stack
# from read_file/write_file/read_dir.
my %err_func = (
'carp' => \&carp,
'croak' => \&croak,
) ;
sub _error {
my( $args, $err_msg ) = @_ ;
# get the error function to use
my $func = $err_func{ $args->{'err_mode'} || 'croak' } ;
# if we didn't find it in our error function hash, they must have set
# it to quiet and we don't do anything.
return unless $func ;
# call the carp/croak function
( run in 0.777 second using v1.01-cache-2.11-cpan-995e09ba956 )