Perl Language File I/O (reading and writing files) Reading from a file


Example

my $filename = '/path/to/file';

open my $fh, '<', $filename or die "Failed to open file: $filename"; 
    
# You can then either read the file one line at a time...
while(chomp(my $line = <$fh>)) {
    print $line . "\n";
}

# ...or read whole file into an array in one go
chomp(my @fileArray = <$fh>); 

If you know that your input file is UTF-8, you can specify the encoding:

open my $fh, '<:encoding(utf8)', $filename or die "Failed to open file: $filename";

After finished reading from the file, the filehandle should be closed:

close $fh or warn "close failed: $!";

See also: Reading a file into a variable

Another and faster way to read a file is to use File::Slurper Module. This is useful if you work with many files.

use File::Slurper;
my $file = read_text("path/to/file"); # utf8 without CRLF transforms by default
print $file; #Contains the file body

See also: [Reading a file with slurp]