AAmit’s LibraryLEARN · PRACTISE · REFLECT

Computers · Programming Atlas

Perl Foundations

Core values, control flow, functions, collections, text, regular expressions, temporary files, expected errors, JSON, local modules and tests. No external data, packages or deployment.

Audience: Learners comfortable saving a source file and running an installed interpreter.

Practice: 4 to 6 hours.

Runtime and boundaries: Perl 5.34.1 is installed; no other Perl version or platform was tested. Run /usr/bin/perl followed by the quoted entry filename in a new practice folder. Save companions beside the entry file. Core libraries only; no package manager is used. The browser exports text and never executes it. Syntax checks are distinct from runtime tests and are not arbitrary-code sandboxes.

Lessons

Pin the installed interpreter

This pack uses Perl 5.34.1 on macOS arm64 and already installed core modules. It uses Perl 5 lexical variables and ordinary subroutines, not Raku or later experimental features. Run /usr/bin/perl followed by the quoted .pl filename. No CPAN or package installation is needed.

Context affects values

Scalar and list context are central to Perl. An array in scalar context yields its count. Use eq for textual equality and == for numeric equality. Scalars can be interpreted as text or numbers, so this pack validates a decimal representation rather than claiming a strict historical type distinction.

Truth and absence

The string "0" is false in ordinary boolean context. Use defined when zero is a valid result. Defined-or // provides a fallback only for undef, unlike ||. Add strict and warnings to expose common mistakes; neither is a sandbox or complete input validator.

Functions and bounded control

Subroutines receive arguments in @_. Copy the values into lexical variables to avoid accidental alias writes. A for loop and next make filtering explicit; ensure while conditions progress. Range and count limits keep every exercise small and deterministic.

References and data structures

Array and hash references represent nested collections. An outer copy still shares nested references. The row-copy exercise duplicates exactly one known depth. Sort hash keys for deterministic reports; do not rely on hash iteration order.

Text, regex and encoding

use utf8 describes the source text, not an I/O handle. File encoding is explicit with :encoding(UTF-8). Quote literal regex content with \Q...\E and anchor whole strings with \A/\z. No dynamic regex code, shell interpolation or string eval is used.

Files, modules and errors

Use three-argument open, lexical handles, checked I/O results and newly created File::Temp directories. Cleanup is verified after normal process exit, not guaranteed after a crash. A module is executable trusted code; use lib adds only the companion directory. eval BLOCK catches expected exceptions; preserve $@ before another operation can change it.

Testing is runtime evidence

perl -c checks syntax but may execute BEGIN/CHECK blocks and use statements. It is not a safe way to inspect arbitrary code. Our invalid fixtures contain no custom compile-time blocks; the strict fixture loads only the trusted core strict pragma. Test::More executes four named runtime cases; JSON::PP parsing and custom shape checks do not establish JSON Schema validity.

Reference cards

Scope: use strict; use warnings; my

Lexical declarations and diagnostics.

Values: $scalar / @array / %hash

One value, ordered list, key/value mapping.

Context: scalar(@array)

Array length rather than its elements.

Comparison: eq / ==

Text equality versus numeric equality.

Truth: defined($value)

Preserve zero when testing for presence.

Flow: for / while / next

Bounded iteration and skipping.

Subroutines: sub / my ($value) = @_

Copy arguments into local variables.

References: [] / {} / -> / @$ref

Construct and access nested structures.

Defaults: //

Use fallback only when left side is undefined.

Patterns: \A / \z / \Q...\E

Whole-string boundaries and literal pattern quoting.

Encoding: use utf8 / :encoding(UTF-8)

Source encoding and file encoding are distinct.

Files: open my $fh, mode, path

Three-argument open separates mode and toy path.

Temporary: File::Temp::tempdir(..., CLEANUP => 1)

New directory; cleanup at normal exit.

Errors: eval { ...; 1 } / $@

Block exception handling; save error immediately.

Modules: package / use lib / use Module

Trusted code loading and namespacing.

Tests: Test::More is / ok

Executed assertions with named TAP output.

Supporting configuration: Run instructions.txt
Perl 5.34.1 is installed; no other Perl version or platform was tested. Run /usr/bin/perl followed by the quoted entry filename in a new practice folder. Save companions beside the entry file. Core libraries only; no package manager is used. The browser exports text and never executes it. Syntax checks are distinct from runtime tests and are not arbitrary-code sandboxes.

Examples and practice

Code below is reading material, not an execution console. Download the edition for the complete example files and companion modules.

Perl 01 - Scalars and context

A scalar holds one value; an array holds a list. An array in scalar context yields its length. In ordinary boolean context undef, numeric zero, the empty string and the string "0" are false. This differs from Ruby. strict and warnings help expose mistakes; they are not security controls.

use strict;
use warnings;
my $name = 'Ada';
my @minutes = (10, 20, 30);
my $count = @minutes;
print "$name: $count sessions\n";
print 'List: ', join(', ', @minutes), "\n";
print 'Zero text is ', ('0' ? 'true' : 'false'), "\n";
print 'Empty text is ', ('' ? 'true' : 'false'), "\n";

Expected:

Ada: 3 sessions
List: 10, 20, 30
Zero text is false
Empty text is false

Intentionally invalid Perl: expected interpreter syntax checker diagnostic containing Global symbol. Expected rejection; not a successful program. No runtime execution follows rejection.

use strict; print $missing;
Perl 02 - Bounded control flow

Use braces around blocks, lexically scoped my variables, and a loop condition that progresses toward stopping. next skips the current iteration. These loops have fixed small bounds.

use strict;
use warnings;
my $total = 0;
for my $value (1 .. 4) {
    next if $value % 2;
    $total += $value;
}
print "Even total: $total\n";
my $remaining = 3;
while ($remaining > 0) { $remaining--; }
print "Remaining: $remaining\n";

Expected:

Even total: 6
Remaining: 0

Intentionally invalid Perl: expected interpreter syntax checker diagnostic containing syntax error. Expected rejection; not a successful program. No runtime execution follows rejection.

my $x = ;
Perl 03 - Subroutines and validation

Copy arguments from @_ into lexical variables. This contract validates a scalar decimal representation and accepts numeric 20 or text "20"; it does not distinguish their historical origin. eval BLOCK catches an exception; the final 1 marks success independently of a false result. It is not string eval.

use strict;
use warnings;
sub double_minutes {
    my ($value) = @_;
    die "invalid minutes\n" unless defined($value) && !ref($value) &&
        $value =~ /\A(?:0|[1-9][0-9]{0,2})\z/ && $value <= 120;
    return $value * 2;
}
print 'Double: ', double_minutes(20), "\n";
my $ok = eval { double_minutes(-1); 1 };
my $error = $@;
print "Negative rejected\n" if !$ok && $error eq "invalid minutes\n";

Expected:

Double: 40
Negative rejected

Intentionally invalid Perl: expected interpreter syntax checker diagnostic containing declare constant item. Expected rejection; not a successful program. No runtime execution follows rejection.

my (3) = (1);
Perl 04 - Hashes and references

References permit nested structures. Dereference each array row explicitly. A hash does not promise report order, so sort keys. Defined-or // falls back for undef while preserving a defined zero.

use strict;
use warnings;
my @sessions = (['read', 20], ['code', 30], ['read', 10]);
my %totals;
for my $row (@sessions) {
    my ($topic, $minutes) = @$row;
    $totals{$topic} = ($totals{$topic} // 0) + $minutes;
}
for my $topic (sort keys %totals) { print "$topic: $totals{$topic}\n"; }
print 'Rows: ', scalar(@sessions), "\n";

Expected:

code: 30
read: 30
Rows: 3

Intentionally invalid Perl: expected interpreter syntax checker diagnostic containing syntax error. Expected rejection; not a successful program. No runtime execution follows rejection.

my $x = [1, 2;
Perl 05 - Literal regex and Unicode

use utf8 declares source encoding; it does not configure file handles. This decoded string length counts characters, not grapheme clusters. \Q...\E quotes literal pattern content; \A and \z anchor the entire string. No untrusted regex or executable regex code is accepted.

use strict;
use warnings;
use utf8;
my $label = "café";
print 'Characters: ', length($label), "\n";
my $literal = 'a+b';
print 'Literal match: ', ('a+b' =~ /\A\Q$literal\E\z/ ? 'yes' : 'no'), "\n";
print 'Different text: ', ('aaab' =~ /\A\Q$literal\E\z/ ? 'yes' : 'no'), "\n";
print 'Trailing newline: ', ("20\n" =~ /\A[0-9]+\z/ ? 'accepted' : 'rejected'), "\n";

Expected:

Characters: 4
Literal match: yes
Different text: no
Trailing newline: rejected
Perl 06 - A disposable UTF-8 file

A new File::Temp directory is created under the practice folder and removed at normal process exit. Three-argument open separates the fixed mode from the filename; lexical handles and checked close expose failures. UTF-8 layers apply at I/O. Cleanup after abrupt termination is not guaranteed; only authored toy paths are used.

use strict;
use warnings;
use utf8;
use File::Temp qw(tempdir);
use File::Spec;
my $dir = tempdir('atlas-perl-XXXXXX', DIR => '.', CLEANUP => 1);
my $path = File::Spec->catfile($dir, 'note.txt');
open my $out, '>:encoding(UTF-8)', $path or die "open write: $!";
print {$out} "café\n" or die "write: $!";
close $out or die "close write: $!";
open my $in, '<:encoding(UTF-8)', $path or die "open read: $!";
my $text = do { local $/; <$in> };
close $in or die "close read: $!";
print 'Characters including newline: ', length($text), "\n";
print "Cleanup scheduled for normal process exit\n";

Expected:

Characters including newline: 5
Cleanup scheduled for normal process exit
Perl 07 - Defined results and error recovery

Use defined when zero is a valid result. The explicit policy rejects signs, spaces, leading zeroes, references and values over 120. Numeric conversion alone can warn yet still produce a partial result; validate the full small representation first.

use strict;
use warnings;
sub minutes {
    my ($text) = @_;
    return undef unless defined($text) && !ref($text) &&
        $text =~ /\A(?:0|[1-9][0-9]{0,2})\z/ && $text <= 120;
    return 0 + $text;
}
for my $text ('20', '0', '121', ' 20', '+20', '20x') {
    my $value = minutes($text);
    print defined($value) ? "$value\n" : "invalid\n";
}

Expected:

20
0
invalid
invalid
invalid
invalid
Perl 08 - A local module

Save AtlasMinutes.pm beside the entry file. FindBin locates that directory; use lib adds this trusted practice directory. The package namespaces its routine and ends with a true value. Loading a Perl module executes code, so do not add an untrusted directory to the module path.

use strict;
use warnings;
use FindBin qw($Bin);
use lib $Bin;
use AtlasMinutes;
print 'Total: ', AtlasMinutes::total([20, 30]), "\n";

Expected:

Total: 50

Companion file: AtlasMinutes.pm

package AtlasMinutes;
use strict;
use warnings;
sub total {
    my ($values) = @_;
    die "array required\n" unless ref($values) eq 'ARRAY' && @$values <= 10;
    my $total = 0;
    for my $value (@$values) {
        die "invalid minutes\n" unless defined($value) && !ref($value) &&
            $value =~ /\A(?:0|[1-9][0-9]{0,2})\z/ && $value <= 120;
        $total += $value;
    }
    return $total;
}
1;
Perl 09 - JSON and shape checks

JSON::PP is already installed. canonical makes object-key output deterministic. The contract checks scalar representations; it does not preserve or certify the JSON distinction between a number and numeric text. Duplicate-name rejection and general schema validation are not implemented. Use tiny authored data, never string eval.

use strict;
use warnings;
use JSON::PP;
my $json = JSON::PP->new->canonical->max_depth(10);
my $encoded = $json->encode({topic => 'read', minutes => 20});
my $data = $json->decode($encoded);
die "wrong contract\n" unless ref($data) eq 'HASH' &&
    join(',', sort keys %$data) eq 'minutes,topic' &&
    !ref($data->{topic}) && defined($data->{topic}) &&
    !ref($data->{minutes}) && defined($data->{minutes}) &&
    $data->{minutes} =~ /\A(?:0|[1-9][0-9]{0,2})\z/ && $data->{minutes} <= 120;
print "$data->{topic}: $data->{minutes}\n";
my $ok = eval { $json->decode('{'); 1 };
print "Malformed JSON rejected\n" unless $ok;

Expected:

read: 20
Malformed JSON rejected
Perl exercise A - An optional average

An array reference keeps the input as one argument. The bounded contract accepts integer decimal representations. Return undef for an empty collection and check defined before using the result.

use strict;
use warnings;
sub average {
    my ($values) = @_;
    die "array required\n" unless ref($values) eq 'ARRAY' && @$values <= 10;
    return undef unless @$values;
    my $total = 0;
    for my $n (@$values) {
        die "invalid minutes\n" unless defined($n) && !ref($n) &&
            $n =~ /\A(?:0|[1-9][0-9]{0,2})\z/ && $n <= 120;
        $total += $n;
    }
    return $total / @$values;
}
printf "Average: %.1f\n", average([10, 20]);
print 'Empty: ', (defined(average([])) ? 'value' : 'absent'), "\n";

Expected:

Average: 15.0
Empty: absent

Practice: Average at most ten minute values in 0..120. Reject invalid inputs and return undef for an empty array.

Perl exercise B - Copy one level deliberately

The first copy duplicates the outer array but shares row references. The second duplicates each row for this structure. Deeper references would still be shared; it is not a general recursive clone.

use strict;
use warnings;
my $original = [['read', 20]];
my $shallow = [@$original];
$shallow->[0][1] = 30;
print "After shallow edit: $original->[0][1]\n";
my $rows = [map { [@$_] } @$original];
$rows->[0][1] = 40;
print "After row edit: $original->[0][1]\n";
print "Separate row: $rows->[0][1]\n";

Expected:

After shallow edit: 30
After row edit: 30
Separate row: 40

Practice: Predict aliasing, then duplicate each row so assigning a numeric cell no longer changes the original.

Perl exercise C - Four real test cases

Installed core Test::More emits a plan and named TAP results. The four cases execute at runtime; perl -c does not run the test assertions. An unexpected failure produces a nonzero exit status.

use strict;
use warnings;
use Test::More tests => 4;
sub double_minutes {
    my ($n) = @_;
    die "invalid minutes\n" unless defined($n) && !ref($n) &&
        $n =~ /\A(?:0|[1-9][0-9]{0,2})\z/ && $n <= 120;
    return $n * 2;
}
is(double_minutes(0), 0, 'zero');
is(double_minutes(20), 40, 'normal');
is(double_minutes(120), 240, 'upper boundary');
my $ok = eval { double_minutes(-1); 1 };
ok(!$ok && $@ eq "invalid minutes\n", 'negative rejected');

Expected:

1..4
ok 1 - zero
ok 2 - normal
ok 3 - upper boundary
ok 4 - negative rejected

Practice: Write four named tests for zero, ordinary input, the upper bound and a rejected negative value.

Prompt templates

These are editable planning prompts in the downloadable workbench; they do not contact an AI service here.

Build a bounded example
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. Provide complete source and companion files, expected stdout and a small input contract. Do not claim tests ran without evidence.
Debug a reproducible failure
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. Separate syntax diagnostics, loading errors and runtime exceptions; preserve a minimal reproduction. Do not claim tests ran without evidence.
Design boundary tests
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. Cover zero, empty, invalid and upper-bound cases; distinguish proposed checks from executed checks. Do not claim tests ran without evidence.
Refactor observable behavior
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. Preserve outputs, exceptions, aliasing and cleanup; explain the regression evidence. Do not claim tests ran without evidence.
Document the actual contract
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. State types or scalar representations, encoding, errors, ownership, runtime limits and real evidence. Do not claim tests ran without evidence.
Explain with practice
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. Use an original small example, predicted output, exercise and separate solution. Do not claim tests ran without evidence.

Further reading

Download the offline edition

Complete Atlas 0.11.0 ZIP (6,079,970 bytes) · 411-page guide and catalogue PDF · Versioned source JSON

Unzip the edition and open Programming and Scripting Atlas.html, Web Foundations.html, Python Foundations.html, SQL Foundations.html, Shell Foundations.html, TypeScript Foundations.html Data Formats Foundations.html, C Foundations.html C++ Foundations.html, Ruby Foundations.html, Perl Foundations.html, Swift Foundations.html, Makefile Foundations.html, awk Foundations.html, sed Foundations.html, jq Foundations.html, XSLT 1.0 Foundations.html, Tcl Foundations.html, Expect Foundations.html or Objective-C Foundations.html locally. The original interactive workbenches retain their offline prompt-building, local presets and export controls. Read the included README before running examples yourself. The workbench does not execute pasted code or call an AI service; prompt text is for you to inspect and use separately.

Version 0.11.0 is pinned here. The other 257 registry entries remain planned; this edition does not claim complete language coverage.

Evidence and limits

Objective-C adds 12 accepted native programs, four separate compiler or warning-policy rejections, 120 root checks and 147 independent native checks. Two rejection fixtures are warnings promoted by -Werror; they are not intrinsic syntax failures. No rejected fixture was executed. Tests dated 26 October 2026 used Apple Clang 21.0.0, ARC, C17 base mode, macOS SDK 27.0 headers and system Foundation 6.9 (5027.0.69) on macOS 27.0.1 arm64. This is introductory macOS/Foundation coverage, not iOS, GNUstep, Objective-C++, UI, concurrency or cross-platform coverage. No sanitizers, leak detector, race analysis, allocation/disk-full/permission fault injection or asynchronous timing tests were run. Trusted authored fixtures and process bounds do not establish an arbitrary-code sandbox.

The pinned Atlas 0.11.0 evidence records 607 browser checks, 55 Python harness checks plus four unittest methods, 74 SQL checks, 515 shell checks across 71 runs, 99 TypeScript checks, 51 Data Formats checks, 119 C checks, 116 C++ checks, 97 Ruby checks, 97 Perl checks, 105 Swift harness checks and 97 Makefile harness checks, 145 awk checks, 145 sed checks, 161 jq checks, 157 XSLT checks, 150 Tcl checks and 161 Expect checks. These are separate measures. Tcl and Expect tests are dated 26 October 2026 on installed Tcl 8.5.9 / Expect 5.45 with Tcl 8.5.9 on macOS arm64. These old versions are recorded teaching evidence, not deployment recommendations. Tcl has 12 accepted programs and Expect has 12 accepted controllers; each has four expected evaluation failures, not static compilation passes. Tcl has nine scenarios, five expected nonzero; Expect has seven scenarios, four expected nonzero. Expect default controllers invoke 15 toy children, including two expected child failures; one scenario also expects a failed child. Controller success does not mean every child succeeds. The authoring release records 100 owned-runner regression checks and 109 independent runner checks separately. Only authored fixtures and retained native child handles are covered. Cooperative cleanup requires event-loop progress; outer-timeout child cleanup remains uncertain without complete wait receipts. The retired PID-inspection branch was not retried. No sign-ins, secrets, network or external application control are taught or tested by this pack. awk and sed are text-processing languages; their examples use fixed authored ASCII input and the C locale with installed awk 20200816 and macOS sed on one platform. jq and XSLT each have 12 accepted examples and four separately rejected programs. jq has 21 scenarios, including five contract errors and one no-result status; XSLT has 20 scenarios, including five terminating messages and one CLI parameter rejection. Expected nonzero outcomes are not successful programs. Tests dated 26 October 2026 used jq 1.7.1-apple and XSLT 1.0 with libxslt 1.1.35/libxml2 2.9.13, fixed trusted programs and tiny authored inputs in the C locale on macOS arm64. These old installed XML libraries are recorded learning environments, not recommendations for untrusted-document processing. No imports, external documents, DTDs, custom/external entities, extension functions or generated source are covered. Command flags and bounds are not a complete sandbox. Standalone XPath remains planned; supporting XPath 1.0 expressions are limited to these XSLT examples. These tests do not establish GNU-tool equivalence, Unicode behavior, arbitrary-script safety or cross-platform portability. Swift has 12 accepted programs and four expected static rejections; Makefile has 12 accepted default targets, four expected parser rejections, eight additional scenarios and one expected recipe failure. Makefile is build scripting, not a general-purpose language. The Swift and Makefile test execution dates remain 25 October 2026. awk and sed tests are dated 26 October 2026. Delivery verification does not replace or refresh test execution dates. TypeScript includes 12 accepted programs executed as JavaScript and nine intentionally invalid cases correctly rejected. Each C/C++ pack has 12 accepted programs run normally and with AddressSanitizer/UndefinedBehaviorSanitizer, plus four expected compiler rejections that are never executed. Ruby and Perl each have 12 syntax-accepted programs executed and four expected syntax rejections; rejected cases are not successful programs. Syntax checks may execute compile-time code and are not arbitrary-code sandboxes. Sanitizer results cover executed paths only; leak detection and allocation-failure injection were not tested and memory safety is not proved.

Tested environments are Chrome 155, CPython 3.9.6, SQLite CLI 3.54.0, macOS sh/Bash 3.2.57/Zsh 5.9, TypeScript 6.0.3, Node 24.18.0 Apple Clang 21.0.0, Ruby 2.6.10p210 and Perl 5.34.1, Apple Swift 6.4 in Swift 6 mode and GNU Make 3.81 on one arm64 macOS host. C uses a C17 subset; C++ uses a C++20 subset with libc++ 220106. Python 3.9.6 is unsupported upstream. Ruby 2.6 is end-of-life upstream; the recorded installed interpreter is not a recommended modern runtime. Data Formats uses installed Tomli 1.0.3 through a private fallback; the Python tomllib branch was not run. No new-installation recommendation, complete language/format conformance, schema certification, hardened untrusted XML parsing or general-purpose execution sandbox is established. Other platforms, browsers and screen readers remain unverified. The 145 official references belong to the saved Atlas review, not fresh website-time verification.