Writing Files in Perl

Here’s the translation of the Go code to Perl, with explanations in Markdown format suitable for Hugo:

Writing files in Perl follows similar patterns to the ones we saw earlier for reading.

use strict;
use warnings;
use File::Slurp qw(write_file append_file);
use IO::File;

sub check {
    my $e = shift;
    die $e if $e;
}

# To start, here's how to dump a string (or just bytes) into a file.
my $d1 = "hello\nperl\n";
check(write_file("/tmp/dat1", $d1, { binmode => ':raw' }));

# For more granular writes, open a file for writing.
my $f = IO::File->new("/tmp/dat2", "w") or die "Could not open file: $!";

# It's idiomatic to close the file immediately after opening it.
END { $f->close if $f; }

# You can write byte strings as you'd expect.
my $d2 = pack("C*", 115, 111, 109, 101, 10);
my $n2 = $f->print($d2);
check($!);
printf("wrote %d bytes\n", $n2);

# A simple string write is also available.
my $n3 = $f->print("writes\n");
check($!);
printf("wrote %d bytes\n", $n3);

# Flush writes to stable storage.
$f->flush();

# Perl's IO::File provides buffered writers.
my $w = IO::File->new("/tmp/dat2", "a") or die "Could not open file: $!";
my $n4 = $w->print("buffered\n");
check($!);
printf("wrote %d bytes\n", $n4);

# Use flush to ensure all buffered operations have been applied to the underlying writer.
$w->flush();

Try running the file-writing code.

$ perl writing-files.pl
wrote 5 bytes
wrote 7 bytes
wrote 9 bytes

Then check the contents of the written files.

$ cat /tmp/dat1
hello
perl
$ cat /tmp/dat2
some
writes
buffered

Next we’ll look at applying some of the file I/O ideas we’ve just seen to the STDIN and STDOUT streams.