Perl Cheatsheet

Data Formats and Dates

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

JSON With Core Modules

use JSON::PP qw(encode_json decode_json);

my $data = decode_json('{"ok":true,"count":2}');
print $data->{count}, "\n";

my $json = encode_json({ ok => 1, names => ["Ada", "Grace"] });

JSON::PP ships with modern Perl. Many production apps use Cpanel::JSON::XS or JSON::MaybeXS for speed and compatibility.

CSV

use Text::CSV;

my $csv = Text::CSV->new({ binary => 1, auto_diag => 1 });
open my $fh, '<:encoding(UTF-8)', 'users.csv' or die $!;
while (my $row = $csv->getline($fh)) {
    my ($name, $email) = @$row;
    print "$name <$email>\n";
}

Avoid splitting CSV with a plain comma regex when quoted fields or embedded commas are possible.

Dates and Times

use Time::Piece;

my $now = localtime;
print $now->strftime('%Y-%m-%d %H:%M:%S'), "\n";

my $day = Time::Piece->strptime('2026-06-23', '%Y-%m-%d');

Use modules for parsing and formatting. For serious timezone work, reach for DateTime from CPAN.

Paths

use File::Spec;
use File::Basename qw(dirname basename);

my $path = File::Spec->catfile('data', 'input.txt');
print basename($path), "\n";
print dirname($path), "\n";

File::Spec avoids hardcoding / or platform-specific path rules.

Directory Traversal

opendir my $dh, 'logs' or die $!;
while (my $entry = readdir $dh) {
    next if $entry =~ /^\.\.?$/;
    print "$entry\n";
}
closedir $dh;

Skip . and ... For recursive walking, use File::Find.

Environment Variables

my $database_url = $ENV{DATABASE_URL} // die "DATABASE_URL missing\n";
$ENV{APP_ENV} = 'test';

Environment variables are strings. Validate required values at startup instead of failing halfway through a job.

Unicode I/O

use open qw(:std :encoding(UTF-8));
open my $fh, '<:encoding(UTF-8)', $path or die $!;

Be explicit about encodings at boundaries. Perl's internal strings and external byte streams are different concerns.