package FileSlurp; #---AUTOPRAGMASTART--- use 5.012; use strict; use warnings; use diagnostics; use mro 'c3'; use English qw( -no_match_vars ); use Carp; our $VERSION = 1.7; no if $] >= 5.017011, warnings => 'experimental::smartmatch'; use Fatal qw( close ); #---AUTOPRAGMAEND--- use base qw(Exporter); our @EXPORT_OK = qw(slurpTextFile slurpBinFile writeBinFile slurpBinFilehandle slurpBinFilePart); use File::Binary; sub slurpTextFile { my $fname = shift; # Read in file in binary mode, slurping it into a single scalar. # We have to make sure we use binmode *and* turn on the line termination variable completly # to work around the multiple idiosynchrasies of Perl on Windows open(my $fh, "<", $fname) or croak($ERRNO); local $INPUT_RECORD_SEPARATOR = undef; binmode($fh); my $data = <$fh>; close($fh); # Convert line endings to a single format. This certainly is not perfect, # but it works in my case. So i don't f...ing care. $data =~ s/\015\012/\012/go; $data =~ s/\012\015/\012/go; $data =~ s/\015/\012/go; # Split the lines, which also removes the linebreaks my @datalines = split/\012/, $data; return @datalines; } sub slurpBinFile { my $fname = shift; # Read in file in binary mode, slurping it into a single scalar. # We have to make sure we use binmode *and* turn on the line termination variable completly # to work around the multiple idiosynchrasies of Perl on Windows open(my $fh, "<", $fname) or croak($ERRNO); local $INPUT_RECORD_SEPARATOR = undef; binmode($fh); my $data = <$fh>; close($fh); return $data; } sub slurpBinFilePart { my ($fname, $start, $len) = @_; # Read in file in binary mode, slurping it into a single scalar. # We have to make sure we use binmode *and* turn on the line termination variable completly # to work around the multiple idiosynchrasies of Perl on Windows my $fb = File::Binary->new($fname); $fb->seek($start); my $data = $fb->get_bytes($len); $fb->close(); return $data; } sub slurpBinFilehandle { my $fh = shift; # Read in file in binary mode, slurping it into a single scalar. # We have to make sure we use binmode *and* turn on the line termination variable completly # to work around the multiple idiosynchrasies of Perl on Windows local $INPUT_RECORD_SEPARATOR = undef; binmode($fh); my $data = <$fh>; close($fh); return $data; } sub writeBinFile { my ($fname, $data) = @_; # Read in file in binary mode, slurping it into a single scalar. # We have to make sure we use binmode *and* turn on the line termination variable completly # to work around the multiple idiosynchrasies of Perl on Windows open(my $fh, ">", $fname) or croak($ERRNO); local $INPUT_RECORD_SEPARATOR = undef; binmode($fh); print $fh $data; close($fh); return 1; } 1; __END__