typestar

File I/O in Perl

The modern open idiom: three arguments, a lexical handle, and or die.

use strict;
use warnings;

# three-arg open with a lexical filehandle
open my $out, ">", "notes.txt" or die "write: $!";
print {$out} "line $_\n" for 1 .. 3;
close $out;

open my $in, "<", "notes.txt" or die "read: $!";
while (my $line = <$in>) {
    chomp $line;
    print "read: $line\n";
}
close $in;

unlink "notes.txt" or die "unlink: $!";

How it works

  1. Three-arg open splits mode from filename; or die $! reports failure.
  2. print {$out} writes to the handle; a statement modifier loops three times.
  3. while (<$in>) reads a line at a time and chomp trims the newline.
  4. unlink deletes the scratch file so the run leaves nothing behind.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
336
Tokens
73
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 58 seconds.

Type this snippet

Step 1 of 3 in Files & modern Perl, step 22 of 27 in Language basics.

← Previous Next →