ZetCode

Perl write file

last modified October 8, 2026

In this article we show how to write files in Perl. We create new files, append to existing ones, check the results of each operation, and delete files.

Writing a file follows the same pattern as reading one. We open a file handle with open, print to it with print or printf, and close it with close. The open mode determines what happens to the file:

Perl write text file

In the first example, we create a new text file and write two lines into it.

main.pl
#!/usr/bin/perl

use v5.34.0;
use warnings;

open my $fh, '>', 'notes.txt'
    or die "Cannot open notes.txt: $!";

print $fh "Perl writes text files.\n";
print $fh "This is the second line.\n";

close $fh or die "Cannot close notes.txt: $!";

say "File written";

We write the data to the file and report the result.

open my $fh, '>', 'notes.txt'
    or die "Cannot open notes.txt: $!";

The three-argument open takes the mode '>' as a separate argument. The mode is set apart from the file name, so the file name is never parsed as part of the mode. Because the handle is a lexical (my $fh), it is closed automatically when it goes out of scope, although we close it explicitly here. If the file cannot be opened, open returns false and die stops the program with the message in $!.

print $fh "Perl writes text files.\n";

print with a file handle as its first argument sends the text to the file instead of to the screen. There is no comma after $fh.

close $fh or die "Cannot close notes.txt: $!";

close flushes buffered data to the file. Output is often written during close, so checking its return value catches errors such as a full disk.

$ perl main.pl
File written

Perl append to file

The >> mode adds data to the end of the file without removing its existing contents. Writing and appending differ only in this mode: > starts with an empty file, while >> keeps what is already there.

main.pl
#!/usr/bin/perl

use v5.34.0;
use warnings;

open my $fh, '>>', 'notes.txt'
    or die "Cannot open notes.txt: $!";

print $fh "This line was appended.\n";

close $fh or die "Cannot close notes.txt: $!";

say "Line appended";

We run this program after the previous example. The existing two lines stay in the file and the new line is added after them.

$ perl main.pl
Line appended

Perl read back written file

In the next example, we read the file back to check its contents. The $. variable holds the current line number.

main.pl
#!/usr/bin/perl

use v5.34.0;
use warnings;

open my $fh, '<', 'notes.txt'
    or die "Cannot open notes.txt: $!";

while (my $line = <$fh>) {

    chomp $line;
    say "$.: $line";
}

close $fh;

The program prints each line of the file together with its number. It shows that the appended line follows the original two.

$ perl main.pl
1: Perl writes text files.
2: This is the second line.
3: This line was appended.

Perl printf to file

printf also accepts a file handle. It formats the data and writes the result to the file, which is useful for tabular reports.

main.pl
#!/usr/bin/perl

use v5.34.0;
use warnings;

open my $fh, '>', 'report.txt'
    or die "Cannot open report.txt: $!";

printf $fh "%-10s %5s\n", 'Item', 'Qty';
printf $fh "%-10s %5d\n", 'apples', 12;
printf $fh "%-10s %5d\n", 'pears', 7;

close $fh or die "Cannot close report.txt: $!";

say "Report written";

Each printf call writes one formatted line. The format %-10s left-aligns the item name in ten columns, and %5d right-aligns the quantity in five.

$ perl main.pl
Report written
$ cat report.txt
Item         Qty
apples        12
pears          7

Perl open failure with or die

open fails when the directory does not exist, the file is not writable, or the path is otherwise invalid. In the next example, the directory missing does not exist.

main.pl
#!/usr/bin/perl

use v5.34.0;
use warnings;

my $file = 'missing/output.txt';

open my $fh, '>', $file
    or die "Cannot open $file: $!";

print $fh "This line is never written.\n";
close $fh;

The or die idiom stops the program when open returns false. The $! variable holds the operating system's error text, which we include in the message.

$ perl main.pl
Cannot open missing/output.txt: No such file or directory at main.pl line 8.

The program ends with a non-zero exit status, and the print line is never reached.

Perl file tests

File test operators check properties of a file without opening it. The -e operator tests existence, -f tests for a regular file, -d tests for a directory, and -s returns the size in bytes.

main.pl
#!/usr/bin/perl

use v5.34.0;
use warnings;

for my $name ('notes.txt', 'report.txt', '.', 'nofile.txt') {

    if (-e $name) {

        if (-d $name) {
            say "$name is a directory";
        } elsif (-f $name) {
            my $size = -s $name;
            say "$name is a regular file, $size bytes";
        }
    } else {
        say "$name does not exist";
    }
}

We check each name before using it. We test for a directory first, then for a regular file, and only ask for the size of a regular file.

$ perl main.pl
notes.txt is a regular file, 73 bytes
report.txt is a regular file, 51 bytes
. is a directory
nofile.txt does not exist

Perl unlink file

The unlink function deletes one or more files. It returns the number of files it removed.

main.pl
#!/usr/bin/perl

use v5.34.0;
use warnings;

my $count = unlink 'notes.txt', 'report.txt', 'nosuch.txt';

say "Deleted $count file(s)";

say -e 'notes.txt' ? 'notes.txt still exists' : 'notes.txt is gone';

We pass three names to unlink. The file nosuch.txt does not exist, so it is not counted, and the return value is 2. A missing file does not cause a warning.

$ perl main.pl
Deleted 2 file(s)
notes.txt is gone

Perl read and write file

The +< mode opens a file for both reading and writing without truncating it. In the next example, we overwrite the first four characters of a file.

main.pl
#!/usr/bin/perl

use v5.34.0;
use warnings;

open my $out, '>', 'data.txt'
    or die "Cannot open data.txt: $!";
print $out "Perl is fun\n";
close $out or die "Cannot close data.txt: $!";

open my $fh, '+<', 'data.txt'
    or die "Cannot open data.txt: $!";

my $first = <$fh>;
print "Before: $first";

seek $fh, 0, 0;
print $fh "PERL";

close $fh or die "Cannot close data.txt: $!";

open my $in, '<', 'data.txt'
    or die "Cannot open data.txt: $!";
print "After: ", <$in>;
close $in;

The example first creates data.txt with >. It then reads the line, moves back to the start with seek, and writes over the beginning of the file. Without seek, the write would start at the end of the line we just read.

$ perl main.pl
Before: Perl is fun
After: PERL is fun

Best Practices

Source

Perl open Documentation

In this article we have written, appended, and checked files in Perl.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all Perl tutorials.