Digitless Capitals
Weekly challenge 330 — 14 July 2025
Week 330: 14 Jul 2025
You are given a string containing only lower case English letters and digits. Write a script to remove all digits by repeatedly removing the first digit and the closest non-digit character to its left.
Example 1 Input: $str = 'cab12' Output: 'c' Round 1: remove '1' then 'b' => 'ca2' Round 2: remove '2' then 'a' => 'c' Example 2 Input: $str = 'xy99' Output: '' Round 1: remove '9' then 'y' => 'x9' Round 2: remove '9' then 'x' => '' Example 3 Input: $str = 'pa1erl' Output: 'perl'
This is a simple one-liner with a while
condition, and
could probably be done using a g
modifier on the regular
expression without losing intelligibility.
We are not told what to do if the string doesn't contain
enough non-digits to allow for removal of all the digits,
for example 'ab123'
. I chose simply to return the string
with the remaining digits in place.
However, in production software it is important to agree with the customer what is to be done if the input is not compliant with the specification. Should the code, for example, throw an error and continue, throw an error and halt execution, or silently perform some different action and continue - as I have done?
An interesting case study is the UK Air Traffic Control outage in 2023, where the software encountered two waypoints in the same flight plan which were identified by the same 5-character string. It was known that such duplications existed, but thought that two such waypoints would never be included in a single flight plan. But they were, and the system - as specified - halted, disruping air traffic for many hours.
So be warned!
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2025-07-14 use utf8; # Week 330 - task 1 - Clear digits use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; use Encode; clear_digits('cab12'); clear_digits('xy99'); clear_digits('pa1erl'); clear_digits('onlyletters'); clear_digits('12345'); clear_digits('sausage1234567x'); clear_digits('su?-00mm ()777ert/£/314il0mr7Ф6e'); sub clear_digits { my ($string); # initialise $string = shift; say qq[\nInput: '$string']; # do it $string = $1 . $2 while $string =~ m|^(.*)[^0-9][0-9](.*)$|; # say it say qq[Output: '$string']; }
Input: 'cab12' Output: 'c' Input: 'xy99' Output: '' Input: 'pa1erl' Output: 'perl' Input: 'onlyletters' Output: 'onlyletters' Input: '12345' Output: '12345' Input: 'sausage1234567x' Output: 'x' Input: 'su?-00mm ()777ert/£/314il0mr7Ф6e' Output: 'summertime'
Any content of this website which has been created by Peter Campbell Smith is in the public domain