LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 3518 min read

Best Practices

The core habits that keep Perl code clean and maintainable - strict scoping, meaningful names, commented regex, and using CPAN wisely.

Introduction

Perl has a well-earned reputation for letting you write dense, hard-to-read code - "write-only Perl," as the joke goes. It does not have to be that way. A handful of consistent habits keep Perl scripts just as readable and maintainable as code in any other language.

What You Will Learn
  • Why use strict and use warnings are non-negotiable.
  • How lexical scoping with my prevents whole classes of bugs.
  • How to keep complex regex readable with the /x flag.
  • When to reach for CPAN instead of writing your own utility function.

Always Enable strict and warnings

This is the single most important habit in Perl. use strict catches typos that would otherwise silently create new global variables, and use warnings flags dozens of likely mistakes - using undef in a numeric context, comparing with the wrong operator, and more.

use strict;
use warnings;
my $total = 0;
for my $n (1..5) {
$total += $n;
}
print "Total: $total\n";
Output

Click Run to see what this code prints.

Prefer my for Lexical Scoping

Declaring variables with my keeps them scoped to the enclosing block, rather than leaking into the whole file (or worse, the whole program) as a global would. This is also what makes Perl closures work - each call to a subroutine that returns a closure gets its own private copy of the enclosed variable.

use strict;
use warnings;
sub make_counter {
my $count = 0;
return sub { return ++$count; };
}
my $counter = make_counter();
print $counter->(), "\n";
print $counter->(), "\n";
print $counter->(), "\n";
Output

Click Run to see what this code prints.

Choose Meaningful Variable Names

Perl's reputation for terse, cryptic code is at least partly a habit, not a requirement of the language. Named intermediate variables cost nothing at runtime and make the intent of a calculation obvious to the next person reading it - including future you.

use strict;
use warnings;
# Hard to understand at a glance
my $x = 19.99 * 3;
# Clear intent
my $unit_price = 19.99;
my $quantity = 3;
my $order_subtotal = $unit_price * $quantity;
print "Subtotal: $order_subtotal\n";
Output

Click Run to see what this code prints.

Comment Complex Regular Expressions

The /x modifier tells Perl to ignore whitespace and # comments inside a regex, letting you spread a dense pattern across multiple lines with explanations attached to each piece - dramatically improving readability for anything beyond a trivial match.

use strict;
use warnings;
my $email = 'jane.doe@example.com';
my $pattern = qr/
^([\w.+-]+) # local part
@
([\w-]+\.[\w.-]+)$ # domain part
/x;
if ($email =~ $pattern) {
print "Local: $1, Domain: $2\n";
}
Output

Click Run to see what this code prints.

Use a Modern Perl Version

A version declaration like use v5.36; bundles in strict, warnings, and say automatically, and unlocks newer syntax such as native subroutine signatures - no more manually unpacking @_ at the top of every subroutine.

use v5.36;
sub greet($name) {
say "Hello, $name!";
}
greet('World');
Output

Click Run to see what this code prints.

Favor CPAN Over Reinventing the Wheel

CPAN (the Comprehensive Perl Archive Network) has well-tested modules for almost anything you might otherwise write yourself. List::Util, part of core Perl, provides functions like sum and max that are easy to get subtly wrong if you write them by hand.

use strict;
use warnings;
use List::Util qw(sum max);
my @scores = (72, 88, 95, 60);
print 'Sum: ', sum(@scores), "\n";
print 'Max: ', max(@scores), "\n";
Output

Click Run to see what this code prints.

Common Mistakes

Avoid These Mistakes
  • Skipping use strict/warnings on "just a quick script" - quick scripts are exactly where typos hide longest.
  • Using single-letter variable names for anything beyond a tiny, obvious loop counter.
  • Writing dense regex with no /x flag and no comments, then forgetting what it does a month later.
  • Sticking with old-style @_ unpacking and two-argument open out of habit instead of adopting modern, safer idioms.
  • Reimplementing a common utility (like summing a list or trimming whitespace) instead of checking CPAN first.

Best Practices Recap

  • Start every file with use strict; use warnings; (or use v5.36; and later).
  • Scope every variable with my as tightly as possible.
  • Choose variable and subroutine names that describe intent, not just type.
  • Use the /x modifier and inline comments for any regex more complex than a single simple match.
  • Reach for well-established CPAN modules before writing common utility logic yourself.
  • Keep subroutines short and focused on one responsibility.

Frequently Asked Questions

Generally yes - many CPAN modules are decades old, extremely well tested, and used in production by large organizations. Pin specific versions and review a module's popularity and maintenance history before adopting it.

Perl 5.36 or later is a reasonable modern baseline, giving you signatures, say, and other quality-of-life features by default with a single use v5.36; line.

At minimum, always keep use strict; use warnings; - it costs nothing and catches real bugs even in a ten-line script. The rest scales up as the script grows.

Key Takeaways

  • use strict; use warnings; (or a modern use v5.36;) should be in every file.
  • my-scoped variables avoid accidental global state and enable closures.
  • Readable names and commented regex pay for themselves the first time someone else reads the code.
  • CPAN modules are usually more reliable than a hand-rolled equivalent.

Summary

None of these practices are exotic - they are the same discipline good developers apply in any language, adapted to Perl's particular idioms. In the final lesson of this course, you will step back and look at where Perl fits in the programming landscape today.

Next Lesson →

Where Perl Is Used Today