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
- Three-arg
opensplits mode from filename;or die $!reports failure. print {$out}writes to the handle; a statement modifier loops three times.while (<$in>)reads a line at a time andchomptrims the newline.unlinkdeletes the scratch file so the run leaves nothing behind.
Keywords and builtins used here
chompclosedieformyopenprintunlinkusewhile
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.
Step 1 of 3 in Files & modern Perl, step 22 of 27 in Language basics.