Perl Exercises
Time to practise! Each exercise has a starter playground that runs as it is and prints a placeholder result, so you can see the expected format. Replace the TODO parts, press Run, and compare your output with the "Expected" lines. If you get stuck, open the solution, but try for a few minutes first.
| # | Exercise | Topics |
|---|---|---|
| 1 | Temperature table | loops, printf |
| 2 | Vowel counter | tr///, subroutines |
| 3 | FizzBuzz | conditionals, modulo |
| 4 | Word frequency | hashes, regex, sorting |
| 5 | Palindromes | lc, reverse, substitution |
| 6 | Grade report | hashes of arrays, List::Util |
| 7 | Date reformatting | captures, named captures |
| 8 | Inventory class | bless, methods, die/eval |
1. Temperature table
Print a conversion table from Celsius to Fahrenheit for 0, 10, 20, 30 and 40 degrees. Use F = C * 9 / 5 + 32 and format each row as 0 C = 32.0 F (Celsius right-aligned in 3 characters, Fahrenheit in 5 with 1 decimal).
Expected first line: 0 C = 32.0 F, last line: 40 C = 104.0 F.
use strict;
use warnings;
# TODO: loop over 0, 10, 20, 30, 40 and use the formula
for my $c (0) {
my $f = 0;
print "$c C = $f F\n";
}0 C = 0 F
Show solution
use strict;
use warnings;
for (my $c = 0; $c <= 40; $c += 10) {
printf "%3d C = %5.1f F\n", $c, $c * 9 / 5 + 32;
}2. Vowel counter
Write count_vowels($text) that returns how many vowels (a e i o u, upper or lower case) a string contains.
Expected: 5 for "Programming in Perl" (o, a, i, i, e) and 5 for "AEIOU xyz".
use strict;
use warnings;
sub count_vowels {
my ($text) = @_;
# TODO: count the vowels (hint: tr/// returns a count)
return 0;
}
print count_vowels("Programming in Perl"), "\n";
print count_vowels("AEIOU xyz"), "\n";0
0
Show solution
sub count_vowels {
my ($text) = @_;
return $text =~ tr/aeiouAEIOU//;
}tr with an empty replacement list leaves the string unchanged and returns how many characters matched.
3. FizzBuzz
For the numbers 1 to 15, print Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of both, and the number otherwise, all on one line separated by spaces.
Expected: 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
use strict;
use warnings;
my @out;
for my $n (1 .. 15) {
# TODO: push "Fizz", "Buzz", "FizzBuzz" or the number
push @out, $n;
}
print "@out\n";1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Show solution
my @out;
for my $n (1 .. 15) {
my $word = ($n % 3 == 0 ? "Fizz" : "") . ($n % 5 == 0 ? "Buzz" : "");
push @out, $word || $n;
}
print "@out\n";Building the word by concatenation handles the "both" case for free; || falls back to the number when the word is empty.
4. Word frequency
Count how often each word occurs in the text below, ignoring case and punctuation. Print the words ordered by count (highest first), then alphabetically, as word: count, for the top 3.
Expected:
the: 4
cat: 2
mouse: 2use strict;
use warnings;
my $text = "The cat chased the mouse. The mouse ran, and the cat slept!";
my %count;
# TODO: fill %count from the words of $text (lowercased)
my @top = sort keys %count; # TODO: sort by count, then by word
print "(no words counted yet)\n" unless %count;
print "$_: $count{$_}\n" for grep { defined } @top[0 .. 2];(no words counted yet)
Show solution
my %count;
$count{lc $_}++ for $text =~ /\w+/g;
my @top = sort { $count{$b} <=> $count{$a} || $a cmp $b } keys %count;
print "$_: $count{$_}\n" for @top[0 .. 2];cat and mouse both appear twice; cat comes first because ties are broken alphabetically.
5. Palindromes
Write is_palindrome($s) that ignores case, spaces and punctuation. Print each phrase followed by yes or no.
Expected:
Never odd or even: yes
Perl: no
A man, a plan, a canal: Panama: yesuse strict;
use warnings;
sub is_palindrome {
my ($s) = @_;
# TODO: clean the string, then compare it with its reverse
return 0;
}
for my $phrase ("Never odd or even", "Perl", "A man, a plan, a canal: Panama") {
print "$phrase: ", (is_palindrome($phrase) ? "yes" : "no"), "\n";
}Never odd or even: no
Perl: no
A man, a plan, a canal: Panama: no
Show solution
sub is_palindrome {
my ($s) = @_;
my $clean = lc($s) =~ s/[^a-z0-9]//gr;
return $clean eq reverse $clean;
}reverse is in scalar context here because eq needs a single value, so it reverses the characters.
6. Grade report
Each student has a list of scores. Print each student (alphabetically) with their average to one decimal place and their best score, then the name of the student with the highest average.
Expected:
ana avg 84.3 best 92
ben avg 71.0 best 80
chen avg 90.0 best 95
Top student: chenuse strict;
use warnings;
use List::Util qw(sum max);
my %scores = (
ben => [62, 80, 71],
ana => [92, 78, 83],
chen => [95, 88, 87],
);
# TODO: print one line per student, then the top student
for my $name (sort keys %scores) {
print "$name\n";
}ana
ben
chen
Show solution
my %avg;
for my $name (sort keys %scores) {
my @s = @{ $scores{$name} };
$avg{$name} = sum(@s) / @s;
printf "%-6s avg %5.1f best %d\n", $name, $avg{$name}, max(@s);
}
my ($top) = sort { $avg{$b} <=> $avg{$a} } keys %avg;
print "Top student: $top\n";sum(@s) / @s divides by the array in scalar context, which is its length.
7. Date reformatting
Convert every date written as DD/MM/YYYY in the text to ISO format YYYY-MM-DD, leaving everything else unchanged.
Expected: Invoices due 2024-03-05 and 2024-12-31; ref 12/2024 stays.
use strict;
use warnings;
my $text = "Invoices due 05/03/2024 and 31/12/2024; ref 12/2024 stays.";
# TODO: one substitution with captures
print "$text\n";Invoices due 05/03/2024 and 31/12/2024; ref 12/2024 stays.
Show solution
$text =~ s{\b(?<d>\d\d)/(?<m>\d\d)/(?<y>\d{4})\b}{$+{y}-$+{m}-$+{d}}g;
print "$text\n";Using {} as delimiters means the slashes in the pattern need no escaping, and named captures make the replacement self-explanatory.
8. Inventory class
Complete the Inventory class: add($item, $qty) increases stock, remove($item, $qty) decreases it and dies with Not enough <item> if there is not enough, and report returns the items sorted by name as item=qty joined with commas.
Expected:
apples=7, pears=2
Error: Not enough pears
apples=7, pears=2use strict;
use warnings;
package Inventory {
sub new { my $class = shift; return bless { stock => {} }, $class }
sub add { my ($self, $item, $qty) = @_; return $self } # TODO
sub remove { my ($self, $item, $qty) = @_; return $self } # TODO
sub report { my $self = shift; return "(empty)" } # TODO
}
my $inv = Inventory->new;
$inv->add(apples => 10)->add(pears => 2)->remove(apples => 3);
print $inv->report, "\n";
eval { $inv->remove(pears => 5); 1 } or print "Error: $@";
print $inv->report, "\n";(empty)
(empty)
Show solution
package Inventory {
sub new { my $class = shift; return bless { stock => {} }, $class }
sub add {
my ($self, $item, $qty) = @_;
$self->{stock}{$item} += $qty;
return $self;
}
sub remove {
my ($self, $item, $qty) = @_;
die "Not enough $item\n" if ($self->{stock}{$item} // 0) < $qty;
$self->{stock}{$item} -= $qty;
return $self;
}
sub report {
my $self = shift;
my $s = $self->{stock};
return join ", ", map { "$_=$s->{$_}" } sort keys %$s;
}
}The stock is unchanged after the failed removal because die happens before the subtraction.
Test yourself
Which expression counts the digits in $s?
$s =~ tr/0-9//length($s =~ /\d/)count($s, '0-9')$s =~ s/\d//
In sum(@s) / @s, what does the second @s evaluate to?
- The first element
- The last element
- The number of elements
- A reference