Perl Weekly Challenge - 358: When Strings Become Numbers and Letters Start Shifting
Source: Dev.to
Challenge 1 — When Strings Become Numbers
Problem
You are given a list of strings. For each string:
- If it contains only digits, treat it as a number.
- Otherwise, treat its length as its value.
Return the maximum of these values.
Examples
| Strings | Interpreted as | Maximum |
|---|---|---|
"123", "45", "6" | 123, 45, 6 | 123 |
"abc", "de", "fghi" | 3, 2, 4 | 4 |
"0012", "99", "a1b2c" | 12, 99, 5 | 99 |
Key Observation
The core of the problem is deciding whether a string is purely numeric. In Perl this is a one‑liner regex.
Solution
use List::Util qw(max);
sub get_value {
my $str = shift;
# Not purely numeric → use length
return length($str) unless $str =~ /^\d+$/;
# Purely numeric → numeric context
return 0 + $str;
}
my $max = max( map { get_value($_) } @strings );
^\d+$checks if the string consists only of digits.length($str)is used for non‑numeric strings.0 + $strforces numeric conversion, turning"0012"into12.maxfromList::Utilfinds the largest value.
Challenge 2 — Caesar Cipher (Letter Shifting)
Problem
Implement a Caesar cipher that shifts every lowercase letter by N positions, wrapping from z to a. All other characters remain unchanged.
| Input | Shift | Output |
|---|---|---|
"abc" | 1 | "bcd" |
"xyz" | 2 | "zab" |
"hello" | 5 | "mjqqt" |
"perl" | 26 | "perl" |
Key Observation
Treat letters as numbers in the range 0‑25 and perform arithmetic modulo 26.
Solution
sub caesar_encrypt {
my ($str, $int) = @_;
$int %= 26; # Normalize shift
my $result = '';
for my $char (split //, $str) {
if ($char =~ /[a-z]/) {
$result .= chr(
(ord($char) - ord('a') + $int) % 26 + ord('a')
);
} else {
$result .= $char;
}
}
return $result;
}
The crucial line:
chr((ord($char) - ord('a') + $int) % 26 + ord('a'))
Steps
- Convert the character to its ASCII code (
ord). - Normalize to a 0‑25 range (
ord($char) - ord('a')). - Add the shift and apply modulo 26 to wrap around.
- Convert back to a character (
chr).
No lookup tables or special cases are needed—just simple arithmetic.
Testing the Solutions
Both challenges were verified with small test suites that print PASS or FAIL for each case. Writing tests, even for short scripts, helps ensure correctness and encourages clean code.
Why These Challenges Are Enjoyable
- Regex makes validation trivial.
- Numeric and string contexts in Perl work naturally together.
- ASCII arithmetic provides a concise way to manipulate characters.
- Functional tools like
mapkeep the code short and expressive.
These seemingly simple problems touch on important concepts such as data interpretation, input validation, and modular arithmetic, all handled elegantly in Perl.