Perl by Example: File I/O
Reading and writing files with this code example demonstrating file handle creation with open function, mode specification for read/write/append, diamond operator for line reading, chomp for newline removal, and error handling with die.
Code
#!/usr/bin/perl
use strict;
use warnings;
my $filename = "test.txt";
# Open file for writing (>)
open(my $fh, '>', $filename) or die "Could not open file '$filename' $!";
print $fh "Line 1\n";
print $fh "Line 2\n";
close $fh;
# Open file for reading (<)
open(my $in, '<', $filename) or die "Could not open file '$filename' $!";
# Read line by line
while (my $row = <$in>) {
chomp $row; # Remove newline character
print "Read: $row\n";
}
close $in;Explanation
File handling in Perl uses the open function to create file handles, which are references to open files. The three-argument form open(my $fh, $mode, $filename) is preferred for security, separating the mode from the filename. Modes include < for reading, > for writing (truncating existing files), and >> for appending. The or die idiom provides error handling, terminating the script with an error message if the operation fails.
The diamond operator <$fh> reads from file handles, returning one line at a time in scalar context or all lines as a list in list context. In a while loop condition, it reads lines sequentially until end-of-file. The chomp function removes trailing newline characters from strings, commonly used after reading lines to get clean text content. The special variable $! contains the system error message when file operations fail.
Writing to files uses print with the file handle as the first argument without a comma, like print $fh "text". The close function explicitly closes file handles, flushing buffers and releasing system resources. File handles are automatically closed when they go out of scope, but explicit closing is considered good practice. The binmode function sets binary mode for file handles, important for cross-platform compatibility when handling binary data.
Code Breakdown
open(my $fh, '>', ...) three-argument form opens file in write mode.or die "..." $! error handling, $! contains system error message.<$in> diamond operator reads one line per iteration until EOF.chomp removes trailing newline character from string.
