Tutorial by Examples

open my $fh, '<', $filename or die "Could not open $filename for reading: $!"; my $contents = do { local $/; <$fh> }; After opening the file (read man perlio if you want to read specific file encodings instead of raw bytes), the trick is in the do block: <$fh>, the ...
Using the idiom from The Manual Way several times in a script soon gets tedious so you might want to try a module. use Path::Tiny; my $contents = path($filename)->slurp; You can pass a binmode option if you need control over file encodings, line endings etc. - see man perlio: my $contents =...
This is a minimalist module that only slurps files into variables, nothing else. use File::Slurper 'read_text'; my $contents = read_text($filename); read_text() takes two optional parameters to specify the file encoding and whether line endings should be translated between the unixish LF or DOS...
Don't use it. Although it has been around for a long time and is still the module most programmers will suggest, it is broken and not likely to be fixed.
open(my $fh, '<', "/some/path") or die $!; my @ary = <$fh>; When evaluated in list context, the diamond operator returns a list consisting of all the lines in the file (in this case, assigning the result to an array supplies list context). The line terminator is retained, and ...
Input record separator can be specified with -0 switch (zero, not capital O). It takes an octal or hexadecimal number as value. Any value 0400 or above will cause Perl to slurp files, but by convention, the value used for this purpose is 0777. perl -0777 -e 'my $file = <>; print length($file)...

Page 1 of 1