Reading and writing files

Open project files with three-argument open and or die, read line by line, and write temporary files under /tmp.

Runs in Zerethon IDE · Perl 5.40 Official Perl documentation ↗

A run sees the project's files in its working folder, read-only. A program may write files under /tmp; they are deleted when the run ends.

main.pl
use v5.40;

open(my $in, "<", "data.csv") or die "Cannot open data.csv: $!";
my $header = <$in>;
my @names;
while (my $line = <$in>) {
    chomp $line;
    my ($name, $score) = split /,/, $line;
    push @names, $name;
    say "$name scored $score";
}
close $in;

open(my $out, ">", "/tmp/report.txt") or die "Cannot write: $!";
say {$out} "count=", scalar @names;
close $out;

open(my $back, "<", "/tmp/report.txt") or die "Cannot read: $!";
print while <$back>;
close $back;
data.csv
name,score
ada,90
alan,85

Output

ada scored 90
alan scored 85
count=2
  • Always check open: or die "...: $!" stops with the reason ($!), such as No such file or directory.
  • Modes: < read, > write (replaces the file), >> append.
  • Paths are relative to the project root: open(my $f, "<", "data/input.txt") reads the file shown in the explorer as data/input.txt.
  • Writing next to your code fails with Read-only file system — use /tmp/out.txt.