Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 43 ยท Practice and Review

Perl Interview Questions

Prepare for a Perl interview: context, my vs local, references, closures, regex, OOP, CPAN and classic pitfalls, each with a clear answer and tested code.

Perl interviews tend to circle around the same ideas: context, scope, references, regular expressions and the habits that keep scripts safe. This page collects the questions you are most likely to meet, with short answers you can say out loud and small code samples to back them up. If an answer feels unfamiliar, the link beside it points to the lesson that explains it in depth.

Perl is not installed on this site, so the Perl code is read-only. Every sample was run on a real Perl 5.42 and the printed output is what that run produced. Two Python stand-ins let you experiment with the regex and sorting ideas in the browser.

What interviewers look for

Core model Context, scope and references.
Regex skill Greedy, anchors, captures.
Safe habits strict, warnings, 3-arg open.
Ecosystem CPAN, tests and modern style.

Explain why, not only what.

1 / 2

Language basics

What is TMTOWTDI?

"There's more than one way to do it", Perl's motto. The language gives you several idioms for most tasks (for or map, if or a statement modifier). The price is that code styles vary, so teams agree on conventions, run perltidy and perlcritic, and always use strict and warnings.

Why use strict and use warnings?

strict makes undeclared variables a compile-time error, so a typo such as $totl is caught right away instead of silently creating a new global. warnings reports suspicious runtime behavior such as using undef in arithmetic or comparing a non-number with ==. use v5.36; (or newer) turns both on. See strict and warnings.

What are the three variable types and their sigils?

Scalars ($x), arrays (@a) and hashes (%h). The sigil describes what you get, not what the variable is: one element of @a is $a[0], and a slice is @a[0,1].

What is truthiness in Perl?

There is no boolean type. False values are undef, the empty string, the number 0 and the string '0'. Everything else is true. The surprise is that '00', '0.0' and ' ' are all true. A run printed:

PERL
for my $v (0, '0', '', '00', '0.0', ' ', 'a', undef) {
    say defined $v ? "'$v'" : 'undef', ' => ', ($v ? 'true' : 'false');
}
TEXT
'0' => false
'0' => false
'' => false
'00' => true
'0.0' => true
' ' => true
'a' => true
undef => false

See conditionals.

What is the difference between == and eq?

== compares numbers and eq compares strings. Mixing them is a classic bug:

PERL
say "10" == 10.0 ? 'num equal' : 'num differ';
say "10" eq "10.0" ? 'str equal' : 'str differ';
say "abc" == 0 ? 'abc is zero' : 'no';
TEXT
num equal
str differ
abc is zero

The last line only works because the text abc silently becomes 0. With use warnings Perl prints a "isn't numeric" warning. The same split exists for <=> and cmp, and for < and lt.

How does Perl treat "5" + "5" and "5" . "5"?

Operators decide the type: + forces numbers and . forces strings, so one gives 10 and the other 55. Perl is weakly typed and converts as needed. "3 apples" * 2 gives 6 (with a warning), because numeric conversion reads the leading digits.

Context

What is context?

Every expression is evaluated in scalar or list context, and the same expression can return different things in each. An array in scalar context gives its length, and in list context gives its elements.

PERL
my @a = (10, 20, 30);
my $count = @a;
my ($first) = @a;
my $last = (10, 20, 30)[-1];
say "$count $first $last";
say "Array has " . @a . " items";
say "Last index $#a";
TEXT
3 10 30
Array has 3 items
Last index 2

The parentheses around my ($first) make it a list assignment, so it takes the first element instead of the count. The concatenation operator provides scalar context, so @a becomes 3. Remember: $#a is the last index and @a in scalar context is the count, which is one more. See context.

What does wantarray do?

It tells a subroutine how it was called: true for list context, false (but defined) for scalar, and undef for void.

PERL
sub ctx { return wantarray ? 'list' : defined(wantarray) ? 'scalar' : 'void' }
my @l = ctx(); my $s = ctx();
say "$l[0] $s";
TEXT
list scalar

How do you count regex matches?

Force list context with an empty list assignment, then use the result in scalar context: my $count = () = $text =~ /x/g;. The right side returns all matches, and a list assignment in scalar context returns the number of items on the right.

Scope

What is the difference between my and local?

my creates a lexical variable that exists only in the enclosing block and is invisible to called subroutines. local does not create a new variable: it saves the current value of a package (global) variable and restores it when the block ends, and every subroutine called in between sees the temporary value (dynamic scope).

PERL
our $level = 'global';
sub show { say "level=$level" }
sub with_my    { my $level = 'my';    show() }
sub with_local { local $level = 'local'; show() }
with_my(); with_local(); show();
TEXT
level=global
level=local
level=global

Prefer my almost always. Use local for special variables such as $_, $/ or $, when you need a temporary change. See scope and closures.

What are our and state?

our declares a lexically scoped alias to a package variable, so it is visible under strict. state (from use feature 'state', included in use v5.10 and later) is a my variable that is initialized once and keeps its value between calls.

What is a closure?

A subroutine that remembers the lexical variables that were in scope when it was created. A common check is a loop that builds subs:

PERL
my @subs;
for my $i (1 .. 3) { push @subs, sub { $i * 10 } }
say join ',', map { $_->() } @subs;
TEXT
10,20,30

Each iteration gets a fresh $i, so each closure keeps its own value.

References and data

What is a reference, and how do you make one?

A reference is a scalar that points to another value. Put a backslash in front of a variable (\@a, \%h, \&f) or use an anonymous constructor ([ ... ], { ... }, sub { ... }). Dereference with @$r, @{ $r }, $r->[0], $r->{key} and $r->@*. See references.

What is the difference between a shallow and a deep copy?

my @copy = @orig; copies the elements, but if they are references, both arrays point at the same inner data:

PERL
my @orig = ([1, 2], [3]);
my @copy = @orig;
push @{ $copy[0] }, 99;
say scalar @{ $orig[0] };
TEXT
3

The original inner array grew too. Storable::dclone makes a full deep copy (nested data).

Do subroutine arguments get copied?

No. @_ holds aliases to the caller's variables, so assigning to $_[0] changes the original. The same is true of foreach, whose loop variable aliases each element.

PERL
my @n = (1, 2, 3);
$_ *= 2 for @n;
say "@n";
sub bump { $_[0]++ }
my $v = 5; bump($v); say $v;
TEXT
2 4 6
6

Good style copies arguments with my ($x) = @_; or a signature, unless aliasing is the point.

What is autovivification?

Perl creates intermediate containers when you use them as references. It makes push @{ $h{$k} }, $x work, but it also means a read like exists $deep{x}{y} creates $deep{x}:

PERL
my %deep;
say exists $deep{x}{y} ? 'y' : 'n';
say exists $deep{x} ? 'x autovivified' : 'x absent';
TEXT
n
x autovivified

exists versus defined on a hash element?

exists asks whether the key is present, defined asks whether its value is not undef. A key can exist with an undefined value: my %h = (a => undef); gives exists true and defined false.

In what order does a hash return its keys?

In no order you can rely on, and it varies between runs. Sort the keys when you need a stable order: for my $k (sort keys %h).

Lists and sorting

What does the default sort do?

It compares as strings. sort 10, 9, 100, 1 gives 1 10 100 9. Use sort { $a <=> $b } for numbers:

TEXT
1 10 100 9
1 9 10 100

Try the same idea in Python, where the type of the values decides the order:

Python String sort versus numeric sort (Python stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In Perl the matching case-insensitive sort is sort { lc($a) cmp lc($b) } @words.

map versus grep versus foreach?

map transforms each element into zero or more results, grep keeps the elements that pass a test, and foreach runs statements for their side effects. Use map and grep when you want a new list, and foreach when you want an action. See list functions.

Regular expressions

Greedy versus lazy quantifiers?

+, * and {n,} take as much as they can, while the same followed by ? take as little as possible.

PERL
my $html = '<b>one</b> and <b>two</b>';
my ($g) = $html =~ /<b>(.+)<\/b>/;
my ($l) = $html =~ /<b>(.+?)<\/b>/;
say $g; say $l;
TEXT
one</b> and <b>two
one

Try it with the same syntax in Python:

Python Greedy versus lazy (Python stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

What do \A, \z, ^ and $ do?

^ and $ match at line boundaries only with /m. Without it, $ also matches before a trailing newline, so use \A and \z for strict validation. See regex basics.

What do /i /g /m /s /x do?

/i ignores case, /g finds all matches (or continues from pos), /m makes ^ and $ match at each line, /s lets . match a newline, and /x allows whitespace and comments inside the pattern. See captures and modifiers.

What is the difference between s/// and tr///?

s/// replaces patterns using regular expressions. tr/// maps single characters one to one (or counts them) and is faster for that job. Both can return the edited copy with /r.

Files, errors and safety

Why use the three-argument open and a lexical filehandle?

open my $fh, '<', $file or die "...: $!" cannot be tricked by a file name that starts with > or |, the handle closes itself when it goes out of scope, and $! tells you why a failure happened. See reading and writing files.

How do you handle errors?

Use die to throw and eval { ... } to catch (or try/catch in recent Perl, or Try::Tiny). After eval, test the result and $@, ideally with exception objects. See errors, die and eval.

What is taint mode?

perl -T marks data from outside the program (arguments, environment, input) as tainted and refuses to use it in dangerous operations such as shell commands until it has been validated by a regex capture. See security.

Modules and OOP

What is CPAN?

The Comprehensive Perl Archive Network, a large archive of reusable modules, installed with cpan or cpanm. Say how you choose a module: recent releases, tests, documentation, bug tracker activity. See CPAN.

use versus require?

use Module LIST runs at compile time and calls import. require Module runs at runtime and does not import anything. use is equal to BEGIN { require Module; Module->import(LIST) }. See packages and modules.

How does object-oriented Perl work?

A class is a package, an object is a reference blessed into it, and a method is a subroutine whose first argument is the object or class name:

PERL
package Counter {
    sub new ($class, %a) { bless { n => $a{start} // 0 }, $class }
    sub inc ($self)      { ++$self->{n} }
}
my $c = Counter->new(start => 5); $c->inc; say $c->inc; say ref $c;
say $c->isa('Counter') ? 'isa' : 'no';
TEXT
7
Counter
isa

Inheritance uses use parent, and method calls are looked up through the class hierarchy. Modern code often uses Moo or the core class feature. See classes and objects and inheritance and roles.

What does local $_ protect against?

Many built-ins use the global $_, so a function that modifies $_ without local may damage the caller's loop. Use for my $item (...) with a named variable, or local $_ = ... when you must use it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between my and local?

    my gives a block-scoped lexical variable. local saves a global's value and restores it at the end of the block, and subs called in between see the new value.
  2. 2. Which values are false in Perl?

    Exactly undef, the empty string, the number 0 and the string '0' are false. A string such as '00' or '0.0' is true.
  3. 3. After my @copy = @orig; where the elements are array references, why does changing an inner array through @copy also change @orig?

    Only the top-level elements are copied, and these are references to the same inner arrays. Use Storable::dclone for a deep copy.
  4. 4. Why use \z and not $ when validating that a whole string is a number?

    In Perl, $ matches at the end or before a trailing newline. \z matches only at the true end of the string.
  5. 5. What does my $n = () = $text =~ /a/g; compute?

    The empty list assignment forces list context for the match, and its value in scalar context is the number of right-hand items.

Summary

  • Know the core model: sigils, truthiness, == versus eq, and scalar versus list context.
  • Explain my, our, local and state, and show a closure.
  • Remember that references share data (shallow copies), @_ aliases, and autovivification creates containers.
  • Sort with an explicit comparator, and distinguish map, grep and foreach.
  • Be fluent with greedy versus lazy, anchors (\A, \z) and the regex modifiers.
  • Use strict, warnings, three-argument open, eval/die, and choose CPAN modules with care.

Finish with the Perl Cheat Sheet.