Read and write files

Three-argument open

open takes a filehandle, a mode and a file name. Always use the three-argument form: it keeps the file name out of the mode string, so a name that starts with a pipe or a greater-than sign cannot change what open does.

The first examples on this page work on one small file, data.txt. Create it in the directory you run the script from, and save each snippet as demo.pl before you run it:

printf 'ok line\nerror: disk full\nfine\n' > data.txt

open my $fh, "<", "data.txt" or die "cannot open data.txt: $!\n";

The four modes you need are < for reading, > for writing, >> for appending, and +< for read and write. The special variable $! holds the reason the call failed.

Read line by line

In scalar context the readline operator returns one line at a time, including its newline, and undef at the end of the file. That makes it the natural condition of a while loop.

open my $fh, "<", "data.txt" or die "open: $!\n"; while (my $line = <$fh>) { chomp $line; print "$line\n" if $line =~ /error/; } close $fh;

perl demo.pl

error: disk full

Do not repeat the test inside the loop with if ($line). A last line that is exactly zero and has no newline is false, so the inner test would skip it even though the read succeeded. The loop condition itself is safe: in while (my $line = <$fh>) Perl tests the assignment for definedness, not for truth, because it recognises the readline operator there.

Write and append

The greater-than mode truncates the file, so every run starts from an empty file. Two greater-than signs append instead, which is what log writers need.

open my $out, ">", "report.txt" or die "write: $!\n"; print $out "total: 42\n"; close $out or die "close: $!\n";

cat report.txt

total: 42

The file holds the one line the script wrote. Check close as well: a full disk often reports the error there, after print has already returned success. The autodie pragma in lesson 6.4 turns all of these checks into automatic exceptions.

Read it all at once

Setting the input record separator to undef makes the next read return the whole file. This is fine for small configuration files and dangerous for gigabyte logs.

The demo measures config.ini, so create that file first:

printf '[main]\nport = 8080\n' > config.ini

open my $fh, "<", "config.ini" or die "open: $!\n"; my $all = do { local $/; <$fh> }; close $fh; print length $all, " bytes\n";

perl demo.pl

19 bytes

The local keyword gives the change a scope, so the rest of the program keeps reading lines normally. Without local, every later read would return whole files.

Encoding layer

Perl works on characters, files hold bytes. Without a layer, a UTF-8 file arrives as a string of bytes and length counts bytes instead of characters. Put the layer in the mode string.

The demo prints the length of every line of names.txt, so create that file first:

printf 'Ada\nGrace\n' > names.txt

open my $fh, "<:encoding(UTF-8)", "names.txt" or die "open: $!\n"; while (my $line = <$fh>) { chomp $line; print length $line, "\n"; }

perl demo.pl

3
5

Both names are plain ASCII here, so 3 and 5 are characters and bytes at once. Add an accented name and the two counts separate: without the layer José gives 5 bytes, with it 4 characters.

Add the same layer on output, >:encoding(UTF-8), or the characters are written as raw bytes and the file breaks for everyone else. Lesson 7.2 shows the one-line way to set this for all filehandles at once.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Why is the three-argument form of open preferred?

    Answer

    It keeps the file name out of the mode string, so a name cannot change what open does

    In the old two-argument form a file name that starts with a pipe or a greater-than sign becomes part of the mode.

  2. What does the readline operator return in scalar context at the end of a file?

    Answer

    undef

    The scalar read returns one line with its newline, and undef once there are no lines left.

  3. What does the > mode do to an existing file?

    Answer

    It truncates the file, so every run starts empty

    > truncates, and >> is the append mode that a log writer needs.

  4. Where does the reason of a failed open end up?

    Answer

    In $!

    $! holds the system error of the last failed call, which is why the die message quotes it.

  5. Why write into do { local $/; <$fh> } rather than just <$fh>?

    Answer

    local $/ makes the next read return the whole file, and the block gives the change a scope

    Without the scope every later read in the program would also return whole files.

  6. What does the :encoding(UTF-8) layer change?

    Answer

    It decodes the bytes as UTF-8, so length counts characters instead of bytes

    The layer is what turns bytes into characters; a file of 5 bytes can be 4 characters.

  7. What does this program print? open my $out, ">", "data.txt" or die "write: $!\n"; print $out "ok line\nerror: disk full\nfine\n"; close $out; open my $fh, "<", "data.txt" or die "open: $!\n"; while (my $line = <$fh>) { chomp $line; print "$line\n" if $line =~ /error/; } close $fh;

    Answer

    error: disk full

    The loop keeps only the line that matches, and chomp removes its newline before the test.

  8. What does this program print on the screen? open my $out, ">", "report.txt" or die "write: $!\n"; print $out "total: 42\n"; close $out or die "close: $!\n"; open my $in, "<", "report.txt" or die "read: $!\n"; print while <$in>;

    Answer

    total: 42

    The print went to the filehandle and the file holds that line; the second half reads the file back and prints it.

  9. What does this program print? open my $out, ">", "config.ini" or die "write: $!\n"; print $out "[main]\nport = 8080\n"; close $out; open my $fh, "<", "config.ini" or die "open: $!\n"; my $all = do { local $/; <$fh> }; close $fh; print length $all, " bytes\n";

    Answer

    19 bytes

    The whole file is read at once by the scoped local $/, and its 19 bytes are counted.

  10. What does this program print? open my $out, ">", "names.txt" or die "write: $!\n"; print $out "Ada\nGrace\n"; close $out; open my $fh, "<:encoding(UTF-8)", "names.txt" or die "open: $!\n"; while (my $line = <$fh>) { chomp $line; print length $line, "\n"; }

    Answer

    3 / 5

    The newlines are chomped, so the two names are 3 and 5 characters long.

Article author: Arthur Isaev