In Part 1, we explored Perl's remarkable ability to make ordinary programming concepts behave in extraordinary ways.
We encountered expressions that change meaning depending on context, variables consisting entirely of punctuation, operators with their own memories, and data structures that create themselves when you look at them.
We also learned that Larry Wall endorsed an unofficial expansion of Perl's name:
Pathologically Eclectic Rubbish Lister.
But we barely scratched the surface.
Because Perl's greatest weirdness isn't necessarily in its syntax.
It's in the extraordinary freedom it gives programmers to redefine what their programs are doing.
And occasionally, what everyone else's programs are doing.
So let's venture into the deeper waters.
Bring a flashlight.
And maybe a rocking chair.
1. Regular Expressions: Perl's Other Programming Language
Let's begin with the feature that helped make Perl famous.
Regular expressions.
Perl didn't invent regexes, but it helped popularize a particularly powerful flavor of them.
And when I say powerful, I mean it.
Let's start innocently.
my $text = "Hello, world!"; $text =~ s/world/Perl/; print $text; Output:
Hello, Perl! Ok.
A little cryptic, perhaps, but efficient.
Now add some capture groups, backreferences, lookarounds, and modifiers.
Before long, you have something resembling a cryptographic key accidentally pasted into your source code.
And then Perl asks:
"Would you like to execute arbitrary Perl code inside that regex?"
Wait. Regexes Can Execute Code?
Yes.
Consider:
my $count = 0; "cat" =~ /c(?{ $count++ })at/; print $count; Output:
1 That (?{ ... }) construct executes Perl code as part of the regex engine's matching process.
Deep breaths.
Your regular expression is executing program statements.
It's no longer merely describing a pattern.
It's doing things.
And Perl also provides (??{ ... }), which can execute Perl code that produces another pattern to be matched dynamically.
So your regular expression can generate more regular expression while it's running.
At some point, you have to wonder whether we're still matching strings or conducting a programming experiment.
To be fair, these features have legitimate uses, and Perl restricts potentially dangerous execution from interpolated patterns unless explicitly enabled.
But they're a spectacular illustration of just how far Perl is willing to take an abstraction.
Regex Replacement Is Also a Programming Environment
Perl's substitution operator has another trick.
The /e modifier evaluates the replacement as code.
my $text = "cats and dogs"; $text =~ s/(\w+)/uc($1)/ge; print $text; Output:
CATS AND DOGS The g means global substitution.
The e means evaluate the replacement as a Perl expression.
So Perl finds each word, executes uc($1), and substitutes the result.
Elegant.
Powerful.
And the kind of feature that makes security auditors develop a nervous twitch when they discover someone has been constructing replacement expressions from untrusted input.
Your Regex Remembers Where It Left Off
Remember the flip-flop operator from Part 1?
Perl's regex engine also has memory.
my $text = "alpha beta gamma"; $text =~ /(\w+)/g; print pos($text), "\n"; $text =~ /(\w+)/g; print pos($text), "\n"; Output:
5 10 The /g modifier, when used in scalar context, maintains a match position associated with the target string.
Subsequent matches can continue from that position.
And pos() lets you inspect or change it.
So your pattern matching can have state beyond the current expression.
This is genuinely useful for building parsers and scanners.
It's also another reminder that Perl occasionally treats seemingly ordinary operators as tiny stateful machines.
And Then There's Catastrophic Backtracking
Consider this pattern:
/^(a+)+$/ Looks harmless.
It matches one or more groups of one or more a characters.
Now feed it a long string of a characters followed by a b.
The pattern can't match.
But the regex engine may spend a lot of of time exploring different ways to divide the a characters into groups before giving up.
For vulnerable patterns and inputs, the work can grow exponentially.
This is called catastrophic backtracking.
It's not unique to Perl, but Perl's powerful backtracking engine makes it particularly relevant.
And yes, similar mistakes can become denial-of-service vulnerabilities when a web application evaluates expensive patterns against attacker-controlled inputs.
Perl provides tools such as atomic groups and possessive quantifiers to control backtracking.
Those tools are useful.
But let's appreciate the situation.
We started with a language for processing text.
We now have a regex engine with embedded code execution, dynamic pattern generation, persistent match state, recursive matching capabilities, and performance characteristics that can become explosive.
Perl's regular expressions aren't merely a feature. They're a programming language that escaped into another programming language.
And somehow, this is still one of Perl's greatest strengths.
2. DWIM: Perl Does What It Thinks You Meant
One of Perl's underlying philosophies is DWIM.
Do What I Mean.
Not necessarily what I wrote.
What Perl thinks I meant.
This sounds wonderful in theory.
It's also a rather ambitious responsibility to assign to a programming language.
Consider:
my $value = "12cats" + 1; print $value; Without numeric warnings enabled, the result is:
13 Perl interprets the leading numeric portion of "12cats" as 12.
Then adds 1.
With warnings enabled, Perl will complain that "12cats" isn't numeric, but the calculation can still produce 13.
And it gets better.
print "cat" == "dog" ? "equal" : "different"; Without warnings:
equal Because == is numeric comparison.
And both nonnumeric strings can be coerced to zero.
So:
0 == 0 True.
Now compare them using eq, Perl's string equality operator, and you get the expected result.
Perl actually has separate operators for numeric and string comparison.
Which is sensible once you understand the system.
But there's a broader philosophy here.
Perl tries very hard to make operations work in whatever context you've created.
Sometimes that means interpreting a string as a number.
Sometimes that means automatically using $_.
Sometimes that means treating a bareword before => as a string.
Sometimes that means providing special behavior for operations such as splitting on whitespace.
The language makes educated guesses.
And sometimes those guesses are brilliant.
Other times, they're the programming equivalent of autocomplete sending a resignation letter to your boss.
To Perl's credit, use strict and use warnings catch many potentially dangerous mistakes.
Modern Perl developers should generally enable both.
But the underlying philosophy remains fascinating.
Most programming languages want you to tell the compiler exactly what you mean.
Perl often tries to meet you halfway.
The problem is that halfway between what you wrote and what you meant isn't always somewhere you'd like to end up.
3. Tied Variables: Your Variable Might Secretly Be an Object
In most programming languages, variables are reasonably honest.
You read one.
You get its value.
You write one.
Its value changes.
Perl considers this unnecessarily predictable.
Enter tie.
Perl allows you to connect a scalar, array, hash, or filehandle to an object that intercepts operations performed on it.
Let's create a particularly obnoxious variable.
package Loud; sub TIESCALAR { bless \my $value, shift; } sub FETCH { print "SOMEONE READ ME!\n"; ${$_[0]}; } sub STORE { print "SOMEONE CHANGED ME!\n"; ${$_[0]} = $_[1]; } package main; tie my $secret, 'Loud'; $secret = 42; print $secret; Output:
SOMEONE CHANGED ME! SOMEONE READ ME! 42 That's right.
An ordinary assignment invoked an object method.
An ordinary variable read invoked another.
The code using $secret doesn't need to know anything about the machinery underneath.
And the possibilities go far beyond printing messages.
A tied hash can transparently store data in a database.
A tied scalar can retrieve information from an external system.
A tied filehandle can implement custom input and output behavior.
This is extraordinarily powerful.
It also means a variable access that looks completely harmless might involve disk operations, network requests, or whatever else the implementing class decides to do.
Imagine asking a programmer whether reading a scalar could trigger a database query.
In Perl, the correct answer is:
"Depends. Who tied it up?"
The lesson: Perl doesn't merely let you overload operators. It can let you redefine what accessing a variable actually means.
4. AUTOLOAD: The Method Doesn't Exist, but We'll Run It Anyway
Most object-oriented languages have a fairly simple rule.
If you call a method that doesn't exist, something goes wrong.
Perl has an alternative proposal.
What if the method doesn't exist, but we pretend it might?
Enter AUTOLOAD.
package Ghost; our $AUTOLOAD; sub AUTOLOAD { my $self = shift; print "You called $AUTOLOAD\n"; } sub DESTROY {} package main; my $object = bless {}, 'Ghost'; $object->this_method_does_not_exist(); Output:
You called Ghost::this_method_does_not_exist No missing-method exception.
No compilation failure.
The method doesn't exist, but Perl found AUTOLOAD and invoked it instead.
The name of the missing method appears in the package's $AUTOLOAD variable.
So your class can inspect the name and decide what to do.
Maybe generate a method dynamically.
Maybe forward the call somewhere else.
Maybe implement a flexible interface where method names correspond to data fields.
Or maybe just pretend everything is fine.
There are legitimate uses for dynamic dispatch like this.
But imagine maintaining a codebase where searching for a method's definition returns absolutely nothing.
Because the method genuinely doesn't exist.
Yet the application has been calling it successfully for years.
Perl has turned "method not found" from an error into an optional design decision.
5. Typeglobs: Let's Manipulate the Symbol Table Directly
And just when you thought AUTOLOAD was sufficiently strange, Perl offers typeglobs.
In Perl, the familiar prefixes $, @, and % distinguish scalars, arrays, and hashes.
But a typeglob, written with *, represents a symbol-table entry containing slots for different kinds of things.
For example, a name can be associated with a scalar, array, hash, subroutine, and other entities.
Now consider:
our $original = 10; *alias = *original; $alias = 99; print $original; Output:
99 We haven't copied the value.
We've aliased the symbol-table entry.
And a full typeglob alias can affect more than just the scalar slot.
Arrays, hashes, subroutines, and other things associated with that symbol name can be aliased too.
This is part of the machinery behind Perl's traditional module import and export system.
Which is clever.
But it's also the kind of language feature that makes you wonder why everyone else bothered inventing encapsulation.
Perl lets you inspect and manipulate some of the structures that other languages generally keep hidden behind the compiler or runtime.
If ordinary metaprogramming is rearranging furniture, Perl's typeglobs let you move the load-bearing walls.
6. CGI-BIN: When the Internet Was a Directory Full of Executables
To understand Perl's historical influence, we need to return to the early web.
Before modern application servers, REST APIs, container orchestration, and eighteen layers of middleware, a web application might simply be an executable script in a directory called cgi-bin.
The Common Gateway Interface, or CGI, provided a way for web servers to execute external programs and communicate with them through environment variables, standard input, and standard output.
A typical Perl CGI script might look like:
#!/usr/bin/perl print "Content-Type: text/html\r\n\r\n"; print "<h1>Hello, Internet!</h1>"; That was a web application.
Well, at least a web response.
A web server could launch the script, pass information about the HTTP request through the CGI environment, and send the script's output back to the browser.
Simple.
Flexible.
And wonderfully direct.
Perl was particularly well suited to this model because it excelled at processing strings, handling files, and generating text.
Of course, there were complications.
Traditional CGI generally involved starting a new process for every request.
That meant interpreter startup and application initialization overhead.
It could also create operational and security headaches.
And parsing form data, managing cookies, handling sessions, validating input, and producing correct HTTP headers all required care.
The CGI.pm module helped a lot with many of these tasks.
It was so important to Perl's early web-development culture that it became practically synonymous with Perl CGI programming.
Interestingly, CGI.pm was removed from Perl's core distribution in Perl 5.22, although it remains available on CPAN.
But here's the thing.
Despite all the jokes, CGI was remarkably successful.
It helped ordinary programmers build dynamic web applications without requiring a massive application framework.
And Perl was one of the languages that made that revolution possible.
Then developers noticed that launching a new Perl interpreter for every request wasn't particularly efficient.
Naturally, someone had an idea.
What if we kept Perl running inside the web server?
Which brings us to one of my favorite chapters in web-development history.
7. mod_perl: Congratulations, Your Web Server Remembers the Previous User
Enter mod_perl.
Instead of launching a fresh Perl interpreter for every request, mod_perl embedded Perl into Apache and allowed Perl code and interpreter state to persist across requests.
The performance benefits could be substantial.
No need to repeatedly start an interpreter.
Previously loaded modules could remain in memory.
Code could be reused.
Database connections and other expensive resources could potentially be retained.
For the time, this was a very attractive proposition.
But it introduced a spectacularly dangerous distinction.
A traditional CGI request generally started with a fresh Perl process. A mod_perl request might inherit application state left behind by an earlier request.
And so the fun begins.
Imagine a badly written authentication routine.
our $authenticated = 0; sub authenticate { my ($username, $password) = @_; if (valid_credentials($username, $password)) { $authenticated = 1; } } Notice anything missing?
The variable is set to true when authentication succeeds.
But it isn't reset when authentication fails.
Under a fresh-process CGI model, the process ends after the request, so this particular stale-state problem normally disappears with it.
Under a persistent interpreter, the variable may remain true.
User Alice logs in successfully.
The worker retains $authenticated = 1.
Later, Bob makes a request handled by that same worker.
Bob supplies an incorrect password.
The function doesn't set $authenticated back to false.
And if the application relies on that variable afterward, Bob may be treated as authenticated.
Congratulations. Your authentication state has become a community resource.
And this isn't merely a hypothetical horror story.
The historical mod_perl Guide explicitly documents this class of mistake, including scenarios where one user could gain access to another user's account because a global variable remained set in a reused server process.
Now, an important technical distinction.
This doesn't mean mod_perl automatically shares session variables between random threads.
In threaded mod_perl configurations, Perl interpreters have their own state, and sharing between threads requires additional mechanisms.
The problem is that requests handled by the same persistent interpreter can encounter state left behind by previous requests.
With multiple server workers or interpreters, the behavior can appear random because different requests land on different workers.
And Perl package namespaces don't automatically isolate state by HTTP user or session.
A package global belongs to its Perl interpreter, not to whichever visitor happens to be using the website.
That's what made these bugs so nasty.
They might disappear when you restarted Apache.
They might work perfectly on a development server.
They might occur only when a particular worker had previously served an administrator.
And testing the same page repeatedly could produce inconsistent results.
There's another especially charming mod_perl trap involving regular expressions.
Remember Perl's /o modifier, which tells the interpreter to compile an interpolated pattern only once at that regex location?
Under persistent execution, the first request's pattern could remain compiled and be used for later requests, even when those requests supplied different search terms.
So you could write code that accepted a search keyword from the user, then accidentally keep searching for the first keyword supplied to that worker.
Not only did your server remember the previous user. Your regex remembered what they were searching for.
The fixes were straightforward in principle:
Keep request-specific state in request-local variables or objects.
Initialize authentication decisions independently for every request.
Avoid using package globals as if they were session storage.
And don't assume a persistent process behaves like a fresh CGI invocation.
But the underlying lesson is broader.
Moving from a process-per-request model to a persistent execution environment changes the meaning of application state.
Perl developers learned that lesson spectacularly.
And modern developers building applications with persistent workers, reused containers, asynchronous services, or shared caches should recognize the problem immediately.
Different decade.
Same class of bug.
8. Source Filters: Why Stop at Changing the Meaning of Variables?
By now we've seen Perl intercept variable access, invent missing methods, manipulate symbol tables, and execute code inside regexes.
Surely there's a limit.
Well.
Perl also has source filters.
A source filter can transform the source text as Perl reads it.
Which means the code the interpreter ultimately compiles might not be the same text you originally wrote.
The legitimate uses include specialized preprocessing and transformations.
But the feature also opens the door to some breathtakingly strange experiments.
You can alter source text before compilation.
You can introduce syntax-like behavior using preprocessing.
You can construct programs whose actual instructions are difficult to recognize from their source.
And naturally, there's a catch.
Traditional source filters operate on text, not on a fully parsed representation of the Perl program.
This makes them notoriously fragile around quoting, comments, regular expressions, and other syntax.
Even Perl's own documentation warns about these limitations.
Which is particularly entertaining given that Perl itself already has an unusually complicated relationship with parsing.
We have a language famous for difficult-to-parse syntax, and someone decided the solution was to let modules rewrite the source before parsing it.
That's commitment.
9. Smartmatch: The Feature That Was Condemned, Then Pardoned
Let's talk about ~~.
The smartmatch operator.
Introduced in Perl 5.10, smartmatch tried to provide a convenient way to compare values according to their types and structures.
Depending on the operands, it could perform different kinds of matching.
Sometimes string comparisons.
Sometimes numeric comparisons.
Sometimes array membership checks.
Sometimes other matching behavior.
Sounds useful.
Except the rules became sufficiently complicated and surprising that smartmatch acquired a reputation for being difficult to reason about.
Its semantics changed during its early releases.
It was subsequently classified as experimental.
Then deprecated in Perl 5.38.
And scheduled for removal in Perl 5.42.
Which would have been a perfectly ordinary ending for an unsuccessful language feature.
Except Perl 5.42 changed course.
After further discussion, removal was postponed indefinitely.
Smartmatch was retained, with explicit feature controls for modern feature bundles.
So the operator went through an extraordinary lifecycle:
Introduced.
Changed.
Declared experimental.
Deprecated.
Scheduled for execution.
Reprieved.
Perl managed to give a comparison operator its own redemption arc.
There's something wonderfully appropriate about that.
A language built around doing things in multiple ways developed an operator that tried to choose the right comparison automatically.
Then the language's developers spent years debating what the right comparison actually was.
And eventually decided the operator should stay, albeit with restrictions.
That's not just programming-language history.
That's philosophy.
10. CPAN: The Internet's Original "There's a Module for That"
We can't finish an article about Perl without discussing CPAN.
The Comprehensive Perl Archive Network.
Established in 1995, CPAN became one of the earliest and most influential large-scale package ecosystems for a programming language.
Long before npm became the default answer to every JavaScript left-padding problem, Perl developers had a vast archive of modules that could be downloaded, installed, tested, and reused.
And CPAN was genuinely transformative.
Database connectivity?
DBI.
HTTP clients?
LWP.
Date and time handling?
DateTime.
Object systems?
Moose.
Web frameworks?
Catalyst, Mojolicious, Dancer, and others.
There were modules for practically every serious programming task.
And, naturally, for a remarkable number of unserious ones.
The Acme Namespace: Where Perl Developers Go to Express Themselves
CPAN has a long tradition of humorous and experimental modules, many living under the Acme:: namespace.
For example:
Acme::Bleach provides a way to make Perl source code appear almost entirely as whitespace.
Yes.
A module for making your source code less visible.
Because apparently Perl wasn't already challenging enough to read.
Then there's Acme::EyeDrops, which can transform Perl programs into visual ASCII-art arrangements.
Executable code shaped like pictures.
A programming technique that makes code review feel like interpreting ancient cave paintings.
These aren't representative of ordinary production Perl development.
But they capture something wonderful about CPAN culture.
It's not merely a software repository.
It's also a laboratory for ideas, experiments, jokes, and things somebody implemented because they wondered whether it was possible.
And sometimes those experiments become genuinely useful technologies.
CPAN Was Also Serious Engineering
Behind the jokes was an impressive technical ecosystem.
Module distributions had standardized packaging conventions.
Dependency information could be declared.
Automated test suites became an important part of the culture.
CPAN Testers gathered reports from many platforms and environments.
Tools such as cpan, cpanm, and local::lib made installing and managing modules more practical.
MetaCPAN made the archive searchable and its documentation accessible.
These ideas helped establish expectations that modern package ecosystems now take for granted.
Of course, installing dependencies wasn't always painless.
Some modules depended on native libraries.
Some needed compilers.
Some behaved differently across operating systems.
And sometimes you discovered that installing one module meant compiling half the known universe.
But unlike the regex sorcery and magical symbol tables, CPAN's legacy is overwhelmingly positive.
It helped make Perl extraordinarily productive.
And its model influenced how later language communities organized and distributed reusable software.
Perl didn't merely help invent dependency hell. It helped invent the infrastructure that made dependency management worth having.
11. Perl Was Weird Because It Was Trying to Be Useful
After two articles, we've covered quite a collection.
A language where expressions change behavior depending on context.
Where zero can be true.
Where a lookup can create data.
Where regular expressions execute code.
Where ordinary variables can secretly delegate to objects.
Where nonexistent methods can run anyway.
Where symbol tables are yours to manipulate.
Where source code can be transformed before compilation.
And where persistent web-server state once caused some truly memorable production disasters.
It's tempting to dismiss all of this as terrible language design.
But that would miss something important.
Perl wasn't designed in a vacuum.
It emerged from a world of Unix tools, shell scripts, text files, system administration, reporting, and ad hoc data manipulation.
The goal wasn't to produce the purest type system or the smallest language specification.
It was to help programmers get useful work done.
Quickly.
Flexibly.
Often with very little code.
And when the early web arrived, Perl was extraordinarily well positioned to take advantage of it.
It could process text.
Manipulate files.
Talk to databases.
Generate HTML.
Automate systems.
And do it all in an environment where developers often had limited resources and needed results immediately.
Perl's philosophy of DWIM and TMTOWTDI came from that pragmatic background.
Sometimes the result was beautiful.
Sometimes it was incomprehensible.
Sometimes it was both.
And to be fair, Perl has continued to evolve. Modern Perl development isn't limited to CGI scripts and punctuation-heavy one-liners. Its contemporary ecosystem includes modern object systems, web frameworks, testing tools, and actively maintained language features.
But Perl never entirely abandoned the personality that made it famous.
The GOAT of Programming Weirdness?
We've now explored the stranger corners of PHP, JavaScript, Python, C#, Java, and Perl.
Every language has surprises.
Every language has historical baggage.
Every language has design decisions that make perfect sense until you encounter them in production.
But Perl occupies a special place.
Other languages occasionally surprise you with something unexpected.
Perl seems to have anticipated that you might want the unexpected behavior, documented it, and provided three alternative syntaxes for invoking it.
And that, I think, is what makes it the GOAT.
Not because it's the best language for every task.
Not because all its design decisions were good.
But because very few languages have ever been so unapologetically themselves.
Larry Wall gave us a language that tried to understand what programmers meant.
Sometimes it succeeded brilliantly.
Sometimes it understood something entirely different.
And sometimes it let the previous user's session hang around long enough to make things really interesting.
A Final Thought: Everyone Has a Perl Phase
I've come to believe that every programmer exists in one of two states:
You are either before your Perl phase or after it.
Before Perl, you believe programming languages should be logical, predictable, and preferably readable by other human beings.
After Perl, you understand that a programming language can be a tool, a philosophy, a practical joke, and a cry for help, sometimes in the same line of code.
You emerge with a deeper appreciation for regular expressions, a healthy suspicion of punctuation, and the unsettling realization that most programming languages are far more restrictive than they strictly need to be.
You may never write another line of Perl.
You may spend the rest of your career pretending that you don't know what a typeglob is.
But something has changed.
You've seen what happens when a programming language stops asking "Should we allow this?" and starts asking "Why the hell not?"
And there's no going back.
You don't really finish learning Perl. You survive it.
And afterward, every other programming language feels just a little bit... supervised.