Peter’s blog ✴ Week 365 ✴ 16 March 2026
THE WEEKLY CHALLENGE
Lots of counting
You are given a string $str consisting of lowercase
English letters, and an integer $k.
Write a script to convert the lowercase string into numbers using alphabet positions (a=1 … z=26), concatenate them to form an integer, then compute the sum of its digits repeatedly $k times, returning the final value.
Example 1 Input: $str = 'abc', $k = 1 Output: 6 Conversion: a = 1, b = 2, c = 3 -> 123 Digit sum: 1 + 2 + 3 = 6 Example 2 Input: $str = 'az', $k = 2 Output: 9 Conversion: a = 1, z = 26 -> 126 1st sum: 1 + 2 + 6 = 9 2nd sum: 9 Example 3 Input: $str = 'cat', $k = 1 Output: 6 Conversion: c = 3, a = 1, t = 20 -> 3120 Digit sum: 3 + 1 + 2 + 0 = 6 Example 4 Input: $str = 'dog', $k = 2 Output: 8 Conversion: d = 4, o = 15, g = 7 -> 4157 1st sum: 4 + 1 + 5 + 7 = 17 2nd sum: 1 + 7 = 8 Example 5 Input: $str = 'perl', $k = 3 Output: 6 Conversion: p = 16, e = 5, r = 18, l = 12 -> 1651812 1st sum: 1 + 6 + 5 + 1 + 8 + 1 + 2 = 24 2nd sum: 2 + 4 = 6 3rd sum: 6
The initial conversion of characters to digits is done using a computed regex:
$a = ord('a') - 1;
$string =~ s|([a-z])|ord($1) - $a|ge;
The repeated summation is done by splitting the numeric string into single digits and summing them.
This is a good example of a solid engineering solution. It shows a structured and clear thinking process, as well as how well you have used the basic features of Perl to accomplish the task at hand. Your implementation is both concise and expressive; thus, demonstrating your mastery of decomposing problems into their components and using clean, idiomatic coding methods in your programming experience.
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2026-03-16 use utf8; # Week 365 - task 1 - Alphabet index digit sum use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; use Encode; alphabet_index_digit_sum('abc', 1); alphabet_index_digit_sum('az', 2); alphabet_index_digit_sum('perl', 3); alphabet_index_digit_sum('supercalifragilisticexpialidocious', 3); alphabet_index_digit_sum('', 6); sub alphabet_index_digit_sum { my ($string, $count, $a, $sum, @digits, $d); # initialise ($string, $count) = @_; $a = ord('a') - 1; # convert string to digits $string =~ s|([a-z])|ord($1) - $a|ge; # sum repeatedly for (1 .. $count) { @digits = split(//, $string); $string = ''; $sum = 0; $sum += $_ for @digits; $string .= $sum; } # report say qq[\nInput: \$str = '$_[0]', \$k = $count]; say qq[Output: ] . ($sum + 0); }
13 lines of code
Input: $str = 'abc', $k = 1 Output: 6 Input: $str = 'az', $k = 2 Output: 9 Input: $str = 'perl', $k = 3 Output: 6 Input: $str = 'supercalifragilisticexpialidocious', $k = 3 Output: 10 Input: $str = '', $k = 6 Output: 0
Any content of this website which has been created by Peter Campbell Smith is in the public domain