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


Example

Before reading and writing text files you should know what encoding to use. See the Perl Unicode Documentation for more details on encoding. Here we show the setting of UTF-8 as the default encoding and decoding for the function open. This is done by using the open pragma near the top of your code (right after use strict; and use warnings; would be appropriate):

use strict;
use warnings;
use open qw( :encoding(UTF-8) :std ); 

The open function creates a filehandle that is used for reading from and/or writing to a file. The open function has the signature

open(FILEHANDLE, MODE, FILEPATH) and returns a false value if the operation fails. The error description is then stored to $!.

Reading

#!/usr/bin/perl
use strict;
use warnings;
use open qw( :encoding(UTF-8) :std ); # Make UTF-8 default encoding

my $file_path = "/path/to/file";
open(my $file_handle, '<', $file_path) or die "Could not open file! $!";

while(my $row = <$file_handle>) {
    print chomp($row), "\n";
}

close $file_handle 
      or warn "Close failed!";

Writing

#!/usr/bin/perl
use strict;
use warnings;
use open qw( :encoding(UTF-8) :std ); # Make UTF-8 default encoding

my $file_path = "/path/to/file";
open(my $file_handle, '>', $file_path) or die "Could not open file! $!";

print $file_handle "Writing to a file";

close $file_handle 
      or warn "Close failed!";

Reading chunks

Opening and reading big files can take some time and resources. If only a small part of the content is required, it might be a good idea to read the content in chunks using the read function which has the signature

read(FILEHANDLE, SCALAR, LENGTH, OFFSET)

FILEHANDLE must be an opened file handle, SCALAR will hold the read data after the operation. LENGTH specifies the number of characters to be read starting from the OFFSET. The function returns the number of characters read, 0 if the end of file was reached and undef in case of an error.

read($file_handle, $data, 16, 0); 

Reads 16 characters from the beginning of the file into $data.