Perl Cheatsheet

Files and I/O

Use this Perl reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Open Files

open my $in, '<', 'input.txt' or die "input.txt: $!";
open my $out, '>', 'output.txt' or die "output.txt: $!";
open my $log, '>>', 'app.log' or die "app.log: $!";

Always use the three-argument open with a lexical filehandle and check $! on failure.

Read Lines

while (my $line = <$in>) {
    chomp $line;
    print "$line\n";
}

my @lines = <$in>;           # all lines at once (list context)
chomp @lines;

Slurp a File

open my $fh, '<', $path or die "$path: $!";
my $content = do { local $/; <$fh> };

Write Files

print $out "hello\n";
printf $out "%s,%d\n", $name, $score;
close $out or die "close failed: $!";

Encoding Layers

open my $fh, '<:encoding(UTF-8)', $path or die "$path: $!";
open my $bin, '<:raw', 'image.png' or die "image.png: $!";
binmode STDOUT, ':encoding(UTF-8)';

File Tests

-e $path                     # exists
-f $path                     # plain file
-d $path                     # directory
-r $path                     # readable
-w $path                     # writable
-x $path                     # executable
-s $path                     # size in bytes (false if empty)
-z $path                     # true if empty

if (-f $path && -r _) { }    # _ reuses the last stat, no extra syscall

Manage Files and Directories

rename 'old.txt', 'new.txt' or die "rename: $!";
unlink 'temp.txt' or die "unlink: $!";
mkdir 'build' or die "mkdir: $!";
rmdir 'build' or die "rmdir: $!";
my @logs = glob '*.log';
my ($size, $mtime) = (stat $path)[7, 9];

Standard Streams

print STDOUT "normal output\n";
print STDERR "error output\n";
my $line = <STDIN>;
chomp $line;

In-Memory Filehandle

my $data = "a\nb\n";
open my $fh, '<', \$data or die $!;
while (my $line = <$fh>) {
    print $line;
}

Command-Line Arguments

my $first = shift @ARGV;
for my $arg (@ARGV) {
    print "$arg\n";
}