Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 43 ยท Practice and Review

Practice Exercises with Solutions

Practice Perl with 25 graded exercises on scalars, lists, hashes, regex, files, references and subroutines. Every exercise has a tested solution.

Reading about Perl teaches you what the language can do. Writing small programs teaches you how it feels. This page has 25 exercises in three levels, each with a worked solution. Try each one on your own first, then compare. There are many correct answers in Perl, so a solution that looks different from ours can still be right.

Perl is not installed on this site, so the Perl solutions are read-only. Every solution was run on a real Perl 5.42 and the output shown is what it printed. Two Python stand-ins at the end let you experiment in the browser with the same ideas.

Every solution assumes use v5.36; at the top, which turns on strict, warnings, say and subroutine signatures.

Three levels

Warm-up (1-8) Scalars, strings, lists, loops.
Core (9-17) Hashes, regex, sorting, tr.
Challenge (18-25) Files, nested data, closures, recursion.

Work through them in order and read the output carefully.

1 / 2

Level 1: warm-up

1. Temperature conversion

Convert 36.6 degrees Celsius to Fahrenheit and print both with one decimal.

PERL
my $celsius = 36.6;
my $fahrenheit = $celsius * 9 / 5 + 32;
printf "%.1f C = %.1f F\n", $celsius, $fahrenheit;
TEXT
36.6 C = 97.9 F

2. String facts

For Programming Perl, print its length, upper-case form, reversed form and the number of vowels.

PERL
my $text = 'Programming Perl';
my $vowels = () = $text =~ /[aeiou]/gi;
say length $text;
say uc $text;
say scalar reverse $text;
say "vowels: $vowels";
TEXT
16
PROGRAMMING PERL
lreP gnimmargorP
vowels: 4

The () = ... trick counts matches: the list assignment happens in list context, and assigning it to a scalar gives the number of items on the right (context). scalar reverse forces string reversal, since reverse in list context reverses a list.

3. Swap

Swap the values of two variables without a temporary variable.

PERL
my ($a1, $b1) = (3, 8);
($a1, $b1) = ($b1, $a1);
say "a=$a1 b=$b1";
TEXT
a=8 b=3

The right side is evaluated completely before the assignment, so this works.

4. FizzBuzz

Print 1 to 15, but Fizz for multiples of 3, Buzz for multiples of 5 and FizzBuzz for both.

PERL
for my $n (1 .. 15) {
    say $n % 15 == 0 ? 'FizzBuzz'
      : $n % 5  == 0 ? 'Buzz'
      : $n % 3  == 0 ? 'Fizz'
      :                $n;
}
TEXT
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

The test for 15 comes first, because a number divisible by 15 is also divisible by 3 and 5.

5. Sum and average

Compute the sum and average of (4, 8, 15, 16, 23, 42).

PERL
use List::Util qw(sum);
my @nums = (4, 8, 15, 16, 23, 42);
my $total = sum @nums;
printf "sum=%d average=%.2f\n", $total, $total / @nums;
TEXT
sum=108 average=18.00

In $total / @nums, the array is used in scalar context, which gives its length.

6. Smallest and largest

Find the smallest and largest of (7, 3, 19, 4, 11) using only sort.

PERL
my @nums = (7, 3, 19, 4, 11);
my @sorted = sort { $a <=> $b } @nums;
say "min=$sorted[0] max=$sorted[-1]";
TEXT
min=3 max=19

Use <=> for numbers. The default sort compares as strings and would put 19 before 3. See list functions.

7. Reverse the words

Reverse the word order of the quick brown fox.

PERL
my $sentence = 'the quick brown fox';
say join ' ', reverse split ' ', $sentence;
TEXT
fox brown quick the

8. Palindrome

Write is_palindrome that ignores case, spaces and punctuation.

PERL
sub is_palindrome ($s) {
    my $clean = lc($s) =~ s/[^a-z0-9]//gr;
    return $clean eq reverse $clean;
}
for my $s ('A man, a plan, a canal: Panama', 'Perl') {
    say "'$s' => ", (is_palindrome($s) ? 'yes' : 'no');
}
TEXT
'A man, a plan, a canal: Panama' => yes
'Perl' => no

The /r modifier returns the edited copy. eq puts reverse in scalar context, so it reverses the string.

Level 2: core

9. Word frequency

Count how often each word occurs in the cat and the hat and the bat. Show the most frequent first, ties in alphabetical order.

PERL
my $text = 'the cat and the hat and the bat';
my %count;
$count{$_}++ for split ' ', $text;
for my $word (sort { $count{$b} <=> $count{$a} || $a cmp $b } keys %count) {
    say "$word: $count{$word}";
}
TEXT
the: 3
and: 2
bat: 1
cat: 1
hat: 1

The || chains two comparisons: if the counts are equal, <=> returns 0, which is false, so the word comparison decides.

10. Invert a hash

Turn a country-to-capital hash into a capital-to-country hash.

PERL
my %capital = (France => 'Paris', Japan => 'Tokyo', Peru => 'Lima');
my %country = reverse %capital;
say "$_ => $country{$_}" for sort keys %country;
TEXT
Lima => Peru
Paris => France
Tokyo => Japan

A hash in list context is a key-value list, and reversing it swaps every pair. If two keys shared a value, one would be lost.

11. Group by length

Group pear fig apple kiwi plum date by word length.

PERL
my @words = qw(pear fig apple kiwi plum date);
my %by_length;
push @{ $by_length{ length $_ } }, $_ for @words;
for my $len (sort { $a <=> $b } keys %by_length) {
    say "$len: @{ $by_length{$len} }";
}
TEXT
3: fig
4: pear kiwi plum date
5: apple

Perl creates the array on first use (autovivification), so push just works. Insertion order is kept inside each group.

12. Extract numbers

Pull every number, including decimals and negatives, out of Order 66: 3 apples cost 4.50, total -12.25.

PERL
my $text = 'Order 66: 3 apples cost 4.50, total -12.25';
my @numbers = $text =~ /-?\d+(?:\.\d+)?/g;
say join ' | ', @numbers;
TEXT
66 | 3 | 4.50 | -12.25

A /g match in list context returns all matches. Read more in captures and modifiers.

13. Validate a date

Check YYYY-MM-DD dates, with month 01-12 and day 01-31, and print the parts using named captures.

PERL
for my $date ('2026-11-07', '2026-13-01', 'yesterday') {
    if ($date =~ /\A(?<y>\d{4})-(?<m>0[1-9]|1[0-2])-(?<d>0[1-9]|[12]\d|3[01])\z/) {
        say "$date: year $+{y}, month $+{m}, day $+{d}";
    } else {
        say "$date: invalid";
    }
}
TEXT
2026-11-07: year 2026, month 11, day 07
2026-13-01: invalid
yesterday: invalid

This checks the format and ranges only. It would accept 2026-02-31, so a real program also uses Time::Local or Time::Piece for calendar rules.

14. Title case

Capitalize every word of the lord of the rings.

PERL
my $title = 'the lord of the rings';
$title =~ s/(\w+)/\u$1/g;
say $title;
TEXT
The Lord Of The Rings

\u in a replacement upper-cases the next character.

15. Remove duplicates

Remove duplicates from b a b c a d, keeping the first occurrence of each.

PERL
my @items = qw(b a b c a d);
my %seen;
my @unique = grep { !$seen{$_}++ } @items;
say "@unique";
TEXT
b a c d

$seen{$_}++ returns the old count: 0 (false) the first time, so ! makes the item pass.

16. Sort by value

Print the scores ana 90, ben 85, cy 90, dee 70 from high to low, names alphabetical on ties.

PERL
my %score = (ana => 90, ben => 85, cy => 90, dee => 70);
for my $name (sort { $score{$b} <=> $score{$a} || $a cmp $b } keys %score) {
    printf "%-4s %d\n", $name, $score{$name};
}
TEXT
ana  90
cy   90
ben  85
dee  70

17. Caesar cipher

Shift letters of Hello, World three places with tr///, decode it back, and count the capital letters.

PERL
my $message = 'Hello, World';
(my $secret = $message) =~ tr/A-Za-z/D-ZA-Cd-za-c/;
say $secret;
(my $plain = $secret) =~ tr/D-ZA-Cd-za-c/A-Za-z/;
say $plain;
my $upper = ($message =~ tr/A-Z//);
say "uppercase letters: $upper";
TEXT
Khoor, Zruog
Hello, World
uppercase letters: 2

tr maps characters one to one, and with an empty replacement it only counts. See substitution and transliteration.

Level 3: challenge

18. Count lines, words and characters

Count them in a multi-line text through a filehandle.

PERL
my $text = "one two three\nfour five\n\nsix\n";
open my $fh, '<', \$text or die "Cannot open: $!";
my ($lines, $words, $chars) = (0, 0, 0);
while (my $line = <$fh>) {
    $lines++;
    $chars += length $line;
    $words += () = $line =~ /\S+/g;
}
close $fh;
say "lines=$lines words=$words chars=$chars";
TEXT
lines=4 words=6 chars=29

Opening a reference to a string gives an in-memory file, which is handy for tests. With a real file, only the open line changes (see reading and writing files).

19. Longest line

Find the longest line and its number.

PERL
my $text = "short\na much longer line here\nmid size\n";
open my $fh, '<', \$text or die $!;
my ($longest, $number) = ('', 0);
while (my $line = <$fh>) {
    chomp $line;
    if (length $line > length $longest) {
        ($longest, $number) = ($line, $.);
    }
}
say "line $number is the longest: '$longest'";
TEXT
line 2 is the longest: 'a much longer line here'

$. holds the number of the line most recently read.

20. Average per group

Group students by class and print count and average mark.

PERL
my @students = (
    { name => 'Ana', class => 'A', mark => 80 },
    { name => 'Ben', class => 'B', mark => 70 },
    { name => 'Cy',  class => 'A', mark => 90 },
    { name => 'Dee', class => 'B', mark => 65 },
);
my %marks;
push @{ $marks{ $_->{class} } }, $_->{mark} for @students;
for my $class (sort keys %marks) {
    my @list = $marks{$class}->@*;
    my $sum = 0;
    $sum += $_ for @list;
    printf "class %s: %d students, average %.1f\n", $class, scalar @list, $sum / @list;
}
TEXT
class A: 2 students, average 85.0
class B: 2 students, average 67.5

21. Default arguments

Write power($base, $exponent) where the exponent defaults to 2.

PERL
sub power ($base, $exponent = 2) {
    my $result = 1;
    $result *= $base for 1 .. $exponent;
    return $result;
}
say power(5);
say power(2, 10);
TEXT
25
1024

22. Counter factory

Write make_counter($start, $step) that returns a function. Each call to that function returns the next number.

PERL
sub make_counter ($start = 0, $step = 1) {
    my $value = $start - $step;
    return sub { $value += $step };
}
my $by_ones = make_counter();
my $by_tens = make_counter(100, 10);
say join ' ', $by_ones->(), $by_ones->(), $by_ones->();
say join ' ', $by_tens->(), $by_tens->();
say $by_ones->();
TEXT
0 1 2
100 110
3

Each returned function is a closure with its own private $value (scope and closures).

23. Memoized Fibonacci

Compute Fibonacci numbers recursively without exponential time.

PERL
use feature 'state';
sub fib ($n) {
    state %memo;
    return $n if $n < 2;
    return $memo{$n} //= fib($n - 1) + fib($n - 2);
}
say join ' ', map { fib($_) } 0 .. 10;
say fib(50);
TEXT
0 1 1 2 3 5 8 13 21 34 55
12586269025

state keeps %memo between calls, and //= computes a value only when none is stored.

24. Dispatch-table calculator

Evaluate 6 * 7, 9 / 0 and 2 ^ 3 with a hash of code references. Report division by zero and unknown operators politely.

PERL
my %ops = (
    '+' => sub ($x, $y) { $x + $y },
    '-' => sub ($x, $y) { $x - $y },
    '*' => sub ($x, $y) { $x * $y },
    '/' => sub ($x, $y) { $y == 0 ? 'cannot divide by zero' : $x / $y },
);
for my $expr ('6 * 7', '9 / 0', '2 ^ 3') {
    my ($x, $op, $y) = split ' ', $expr;
    my $code = $ops{$op};
    say "$expr = ", $code ? $code->($x, $y) : "unknown operator '$op'";
}
TEXT
6 * 7 = 42
9 / 0 = cannot divide by zero
2 ^ 3 = unknown operator '^'

25. Flatten

Flatten (1, [2, [3, 4]], [[5]], 6) into one list, however deep the nesting goes.

PERL
sub flatten (@items) {
    return map { ref $_ eq 'ARRAY' ? flatten(@$_) : $_ } @items;
}
my @nested = (1, [2, [3, 4]], [[5]], 6);
say join ',', flatten(@nested);
TEXT
1,2,3,4,5,6

ref tells arrays from plain values, and the function calls itself for each inner array (references).

Experiment in the browser

These two Python stand-ins repeat ideas from exercises 9 to 13. Change the text and see what happens.

Python Word frequency and inverted mapping (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.

Python Dates with named groups (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.

Notice that 2026-02-31 passes the pattern. A regex checks the shape of a date, not the calendar.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does sort { $a <=> $b } @nums use <=> and not the default sort?

    Without a block, sort compares values as strings in alphabetical order. <=> compares numerically.
  2. 2. In my $count = () = $text =~ /a/g;, what does $count hold?

    The match runs in list context because of the empty list assignment. Assigning a list assignment to a scalar yields the number of right-hand items.
  3. 3. What makes grep { !$seen{$_}++ } @items keep only the first occurrence of each item?

    $seen{$_}++ returns the value before incrementing. It is 0 or undef the first time, so ! makes the item pass, and later it is positive, so ! rejects it.
  4. 4. Which tool tells an array reference apart from a plain value in the flatten exercise?

    ref returns 'ARRAY' for an array reference and an empty string for non-references.

Summary

  • Warm-up exercises train context, sort, join, split and small subroutines.
  • Hashes solve counting, grouping, inverting and de-duplication problems in a few lines.
  • Regex features such as /g in list context, named captures, /r and tr replace many loops.
  • Closures, state and recursion with ref make subroutines flexible.
  • Regexes check shape, not meaning: validate calendar dates with a date module.

Next: Perl Interview Questions.