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

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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]



Got any Perl Language Question?