Perl interview questions, from context and regex to legacy code

Perl interview questions focus on context, references and regular expressions: whether you know what an array returns in scalar context, how to build and walk nested data with references, and how to write a regex that is correct and readable. Expect questions on strict and warnings, my versus local, packages and bless, error handling with eval, one-liners, DBI and how you would test and modernize old Perl code. Most Perl roles today maintain important systems, so judgment about legacy code matters as much as syntax.

By Published 8 min read

Where Perl shows up in interviews today

Perl still runs a lot of infrastructure: build and release scripts, log processing, bioinformatics pipelines, telecom and finance back ends, monitoring checks and older web applications. New projects in Perl are less common, so many interviews are for roles that maintain, extend or migrate existing code, often alongside Linux administration, Python or SQL. Expect questions that check you can read dense Perl written by someone else, not only write your own. Interviews usually mean Perl 5; Raku (once called Perl 6) is a separate language, and it is worth saying so if asked.

  1. Language screenContext, references, regex and scoping, often as "what does this print?" questions on short snippets.
  2. Practical taskParse a log or CSV file, summarize it in a hash and print a report; sometimes a one-liner challenge.
  3. Code readingA page of older Perl with bugs or bad practices. You explain what it does and what you would fix first.
  4. Systems discussionFor DevOps or back-end roles: DBI, file handling, processes, CPAN dependencies, deployment and tests.

Fundamentals: sigils, context and references

Core Perl questions, what they test, and what a strong answer shows
QuestionWhat it testsWhat a strong answer shows
What do the sigils $, @ and % mean?BasicsScalar, array and hash variables; the sigil shows what you are getting, so one element of @arr is written $arr[0]
What is context, and why does it matter?ContextExpressions behave differently when a scalar or a list is expected; an array in scalar context gives its length
Why use strict and warnings?Habitsstrict catches undeclared variables, symbolic references and barewords; warnings flag likely mistakes such as undef in a string
How do you create and use a reference to an array or hash?ReferencesBackslash to take one or [ ] and { } for anonymous ones, then dereference with -> or @{ } and %{ }
How do you build an array of hashes, or a hash of arrays?Nested dataStore references as values, and use autovivification knowingly, since it can create keys you did not mean to
What is the difference between exists, defined and a true value?Hash semanticsexists checks the key, defined checks the value is not undef, truth also rejects 0 and the empty string
What does wantarray do?Context in subsTells a sub whether it was called in list, scalar or void context so it can return accordingly
How are arguments passed to a sub?SubroutinesThrough @_, whose elements are aliases to the caller's values; copy them into my variables before changing them
Core Perl questions, what they test, and what a strong answer shows. Scroll sideways on a small screen.
use strict;
use warnings;

my @arr  = (10, 20, 30);
my $n    = @arr;          # scalar context: number of elements
my ($first) = @arr;       # list context: first element
my $last = $arr[-1];
print "$n $first $last\n";          # 3 10 30

my %user = (name => 'Ana', roles => ['admin', 'dev']);
my $ref  = \%user;
print "$ref->{name} has ", scalar @{ $ref->{roles} }, " roles\n";
push @{ $ref->{roles} }, 'ops';
print join(',', @{ $user{roles} }), "\n";  # admin,dev,ops
Context and nested data (run with perl 5.34)

Regular expressions and text processing

  • What is the difference between greedy and non-greedy matching? .* takes as much as it can and backtracks; .*? takes as little as possible. Show where the greedy version swallows too much, such as matching HTML-like tags.
  • What do the /g, /i, /x, /s and /m modifiers do? Global matching, case-insensitive, extended mode with whitespace and comments, dot matching newlines, and ^ and $ matching at line boundaries.
  • How do named captures work? (?<name>...) in the pattern, then $+{name} after a match. They make long patterns readable and survive reordering of groups.
  • What is the difference between s/// and tr///? Substitution works with patterns; tr maps characters one to one and returns a count, which is handy for counting characters.
  • Why check whether a match succeeded before reading a capture? Numbered capture variables keep their value from the last successful match, so a failed match can leave stale data from an earlier line. Test the match in an if, or assign the captures in list context.
  • How would you split a CSV line safely? Not with split on commas, because quoted fields can contain commas; use a module such as Text::CSV.
use strict;
use warnings;

my @lines = (
    '2026-03-01 12:00:01 ERROR db timeout after 30s',
    '2026-03-01 12:00:05 INFO request ok',
    '2026-03-01 12:01:10 ERROR db timeout after 30s',
    '2026-03-01 12:02:00 WARN slow query',
);

my %count;
for my $line (@lines) {
    next unless $line =~ /^(?<date>\S+) \s (?<time>\S+) \s (?<level>[A-Z]+) \s (?<msg>.*)$/x;
    $count{ $+{level} }++;
}

for my $level (sort { $count{$b} <=> $count{$a} or $a cmp $b } keys %count) {
    printf "%-5s %d\n", $level, $count{$level};
}
# ERROR 2
# INFO  1
# WARN  1
Count log levels with a named-capture regex (run with perl 5.34)

Interviewers often ask why the sort block uses <=> first and cmp second: the first orders by count numerically, the second breaks ties alphabetically so the output is stable. In /x mode literal spaces are ignored, which is why the pattern uses \s between fields.

One-liners

Operations and DevOps interviews love one-liners. Know -e (code), -n (loop over lines), -p (loop and print), -l (handle newlines), -a with -F (split into @F) and -i (edit in place, with a backup suffix).

# second column, skipping rows whose first column is b   -> 1, 3
perl -lane 'print $F[1] if $F[0] ne "b"' t.txt

# sum the second column                                     -> 6
perl -lane '$s += $F[1]; END { print $s }' t.txt

# replace the word x with X in place, keeping t.txt.bak
perl -pi.bak -e 's/\bx\b/X/g' t.txt
One-liners on a three-line file "a 1 x / b 2 y / c 3 z" (run with perl 5.34)

Scoping, subroutines, packages and objects

Intermediate Perl questions
QuestionWhat it testsWhat a strong answer shows
What is the difference between my, our and local?Scopingmy is lexical; our declares a package variable you can use under strict; local temporarily saves and restores a global's value for a dynamic scope
When is local the right tool?Practical scopingChanging a special variable such as $/ or $, for one block without leaking the change
How does Perl do object orientation?OO modelA package is a class, bless ties a reference to it, methods are subs receiving the object first, and @ISA or parent sets inheritance
Why would a team use Moo or Moose?Modern OODeclared attributes, types, defaults and roles instead of hand-written constructors and accessors
What is a closure, and when have you used one?ClosuresA sub that keeps access to lexical variables from where it was defined, used for counters, callbacks and iterators
How do modules get loaded, and what does use do at compile time?Modulesuse is require plus import at compile time; require loads at run time, useful for optional dependencies
How do you manage CPAN dependencies for a project?ToolingA cpanfile with versions, a tool such as cpanm or Carton to install them, and the same versions in every environment
Intermediate Perl questions. Scroll sideways on a small screen.
use strict;
use warnings;

sub make_counter {
    my $count = shift // 0;
    return sub { return $count++ };
}

my $c1 = make_counter(5);
my $c2 = make_counter();
print $c1->(), $c1->(), $c2->(), "\n";   # 560

my $ok = eval { die "bad input\n"; 1 };
print "caught: $@" unless $ok;          # caught: bad input
A closure counter and eval-based error handling (run with perl 5.34)

The eval { ...; 1 } pattern matters: checking the return value rather than only $@ avoids cases where $@ is cleared or overwritten before you read it. Many codebases use Try::Tiny or, on newer Perls, the built-in try feature instead.

Senior and scenario questions

  • How do you query a database from Perl safely? DBI with placeholders and bound values, never interpolating input into SQL, with RaiseError on and transactions where several statements must succeed together.
  • How do you open a file the modern way? Three-argument open with a lexical filehandle, an explicit encoding layer where needed, and or die with the file name and $!.
  • You inherit a 3,000-line script with no tests. Where do you start? Add strict and warnings carefully, write characterization tests around current behavior, then extract functions one at a time.
  • A Perl job got slow after a data increase. How do you find out why? Profile with Devel::NYTProf, look for repeated work in loops, regexes compiled inside hot paths, and reading whole files into memory.
  • How do you test Perl code? Test::More with prove, small units for parsing logic, fixtures for files, and mocks for external calls.
  • When would you rewrite Perl in another language, and when would you not? Rewrite when the code blocks needed changes, hiring is hard or the platform is going away; keep it when it is stable, tested and cheap to run.
  • What is the Schwartzian transform? A map-sort-map pattern that computes an expensive sort key once per item instead of on every comparison.
  • What is taint mode? A -T flag that marks outside input as tainted and stops it reaching risky operations until it has been checked with a regex.
  • How do you handle Unicode correctly? Decode input at the edges, use utf8 for source with non-ASCII text, set output encoding layers, and know the difference between bytes and characters in length.
use strict;
use warnings;

my @files = ('report-12.txt', 'report-3.txt', 'report-100.txt');
my @sorted =
    map  { $_->[1] }
    sort { $a->[0] <=> $b->[0] }
    map  { [ /(?<n>\d+)/ ? $+{n} : 0, $_ ] }
    @files;
print "@sorted\n";   # report-3.txt report-12.txt report-100.txt
Schwartzian transform: sort by the number inside each name (run with perl 5.34)

Fictional example

Answering "Tell me about legacy Perl you improved"
At a logistics company I took over a nightly Perl script that matched carrier invoices to shipments. It had no tests and often failed on odd files. First I collected a month of real input files and wrote Test::More checks that recorded what the current script produced, warts included. Then I turned on strict, which flagged eleven undeclared variables, two of them typos that silently dropped rows. I moved the parsing into a module with small functions and replaced a hand-written CSV split with Text::CSV, which fixed the quoted-comma failures. Failed runs went from about one a week to none in the next quarter. The tests made each change safe to ship.

A two-week Perl practice plan

  • Days 1 to 3: context, references and nested data. Build a hash of arrays from a file and print it sorted three ways.
  • Days 4 to 6: regular expressions, named captures, substitutions and tr, then ten one-liners on real log files.
  • Days 7 to 9: scoping, closures, packages and bless, then the same class rewritten with Moo.
  • Days 10 to 12: DBI with placeholders against a local SQLite file if you already have one, Test::More, and profiling a slow loop.
  • Days 13 and 14: read an old CPAN module or a legacy script, list five improvements, and explain them out loud in ten minutes.

Perl roles often sit next to Linux and scripting work. The Linux interview questions cover processes, permissions and shell tools that come up in the same loops, and MATLAB and R pages cover two other languages common in science and analytics teams that still run Perl pipelines.

Perl puzzles are mostly about reading code aloud and saying what it prints. Practicing that with Natively, an AI interview assistant for Mac and Windows, gives you a transcript of your mock session to check where you guessed. While you practice it can read a snippet from a screenshot, offer a hint or a step-by-step outline, and on Pro or the free trial take your résumé and the job description into account. Past sessions and notes are kept for review.

Questions people ask

What are common Perl interview questions?

What scalar and list context mean, how references and nested data work, greedy versus non-greedy regex, my versus our versus local, how bless creates objects, how to handle errors with eval, and how to query a database safely with DBI.

Is Perl still used, and what do Perl interviews focus on?

Yes, especially in build systems, log processing, bioinformatics, telecom and finance back ends. Many roles maintain existing code, so interviews test reading and improving older Perl as well as writing new scripts.

Do Perl interviews include one-liners?

Often, for operations and DevOps roles. Know -e, -n, -p, -l, -a with -F and -i for in-place edits, and be able to sum a column or filter lines from a log on the spot.

Should I learn Raku for a Perl interview?

Usually not. Interviews almost always mean Perl 5. Raku is a separate language that began as Perl 6; it is enough to know the difference if asked.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP