File I/O
Perl reads and writes files through filehandles. You open a handle, read or print through it, and close it. The same operations work on real files, on standard input/output, and on in-memory files (strings opened as if they were files), which is what the examples here use, since the online runner has no file system for you.
Opening a file
The modern form of open takes three arguments: a lexical handle variable, a mode, and the file name:
open(my $in, '<', 'data.txt') or die "Cannot read data.txt: $!";
open(my $out, '>', 'report.txt') or die "Cannot write report.txt: $!";
open(my $log, '>>', 'app.log') or die "Cannot append to app.log: $!";| Mode | Meaning |
|---|---|
< |
read |
> |
write (creates the file, or empties an existing one) |
>> |
append to the end |
+< |
read and write |
open returns false on failure, and $! holds the operating system's error message ("No such file or directory"). Always check it with or die.
Tip: Avoid the old two-argument form
open(FH, $name)and bareword handles likeFH. The three-argument form withmy $fhis safer and the handle closes automatically when the variable goes out of scope.
Reading line by line
<$fh> (the "readline" or "diamond" operator) returns the next line, including its newline, and undef at end of file. Here an in-memory string stands in for a file; the only difference from a real file is the \$text reference in place of a file name:
use strict;
use warnings;
my $text = <<'END';
alice,admin
bob,editor
carol,viewer
END
open(my $fh, '<', \$text) or die "Cannot open: $!";
while (my $line = <$fh>) {
chomp $line;
my ($user, $role) = split /,/, $line;
print "Line $.: $user has role $role\n";
}
close($fh);Line 1: alice has role admin
Line 2: bob has role editor
Line 3: carol has role viewer
$. is the current line number of the last handle read. (<<'END' is a here-doc, the topic of the next lesson.)
Reading everything at once
In list context <$fh> returns all remaining lines. To get the whole file as one string, set $/ (the input record separator) to undef locally, which is known as "slurping":
use strict;
use warnings;
my $text = "first\nsecond\nthird\n";
open(my $fh, '<', \$text) or die $!;
my @lines = <$fh>;
close $fh;
chomp @lines;
print "Got ", scalar(@lines), " lines; last is '$lines[-1]'\n";
open($fh, '<', \$text) or die $!;
my $content = do { local $/; <$fh> };
close $fh;
print "Slurped ", length($content), " characters\n";Got 3 lines; last is 'third'
Slurped 19 characters
Slurping is fine for small files. For big ones, process line by line so memory use stays constant.
Writing
print and printf take an optional filehandle before the list, with no comma after it. Writing to an in-memory handle appends to the string variable:
use strict;
use warnings;
my $report = "";
open(my $out, '>', \$report) or die $!;
my %sales = (north => 1200, south => 950, east => 1430);
print $out "REGION REPORT\n";
for my $region (sort keys %sales) {
printf $out "%-6s %6d\n", $region, $sales{$region};
}
close $out;
print "The report has ", length($report), " characters:\n";
print $report;The report has 56 characters:
REGION REPORT
east 1430
north 1200
south 950
With a real file name instead of \$report, the same code writes a file to disk. print STDOUT ... and print STDERR ... use the standard handles explicitly.
The DATA section
Anything after a line containing __DATA__ (or __END__) is not code: Perl makes it readable through the special filehandle DATA. It is perfect for small embedded data sets, tests and examples:
use strict;
use warnings;
my %total;
while (my $line = <DATA>) {
chomp $line;
next if $line =~ /^\s*(#|$)/; # skip comments and blank lines
my ($date, $category, $amount) = split /\s+/, $line;
$total{$category} += $amount;
}
printf "%-10s %8.2f\n", $_, $total{$_} for sort keys %total;
__DATA__
# date category amount
2024-06-01 food 12.50
2024-06-01 travel 40.00
2024-06-02 food 8.25
2024-06-03 books 23.90
2024-06-03 food 15.00books 23.90
food 35.75
travel 40.00
File tests
Before opening a real file you can check it with file test operators such as -e (exists), -f (is a plain file), -d (is a directory), -r (readable) and -s (size in bytes, or false when empty):
my $path = 'config.ini';
if (-e $path) {
printf "%s is %d bytes\n", $path, -s $path;
} else {
warn "$path not found, using defaults\n";
}Test yourself
Which open mode empties an existing file before writing?
<>>>+<
What does <$fh> return at the end of the file?
- An empty string
- 0
undef- -1
Which line prints to the handle $out correctly?
print $out, "hi\n";print $out "hi\n";print("hi\n" => $out);$out->print "hi";