Broken keys and
mixed up words
Weekly challenge 341 — 29 September 2025
Week 341: 29 Sep 2025
You are given a string, $str
and a character in the given string, $char
.
Write a script to reverse the prefix upto the first occurrence of the given $char
in $str
and return the new string.
Example 1 Input: $str = 'programming', $char = 'g' Output: 'gorpramming' Reverse of prefix 'prog' is 'gorp'. Example 2 Input: $str = 'hello', $char = 'h' Output: 'hello' Example 3 Input: $str = 'abcdefghij', $char = 'h' Output: 'hgfedcbaij' Example 4 Input: $str = 'reverse', $char = 's' Output: 'srevere' Example 5 Input: $str = 'perl', $char = 'r' Output: 'repl'
The essence of my solution is this:
if ($string =~ m|(.*?)$char(.*)|) { $result = $char . reverse($1) . $2; }
That would suffice except for the case where $char
doesn’t
occur in $string
. Of course the task statement excludes
that possibility, but I feel it is prudent to check.
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2025-09-29 use utf8; # Week 341 - task 2 - Reverse prefix use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; use Encode; reverse_prefix('programming', 'g'); reverse_prefix('hello', 'h'); reverse_prefix('goodbye', 'e'); reverse_prefix('noitulos', 's'); reverse_prefix('conundrum', 'z'); sub reverse_prefix { my ($string, $char, $result); # initialise ($string, $char) = @_; # do as instructed if ($string =~ m|(.*?)$char(.*)|) { $result = qq['$char] . reverse($1) . qq[$2']; # non-compliant data! } else { $result = qq[There is no '$char' in '$string']; } say qq[\nInput: \$string = '$string', \$char = '$char']; say qq[Output: $result]; }
Input: $string = 'programming', $char = 'g' Output: 'gorpramming' Input: $string = 'hello', $char = 'h' Output: 'hello' Input: $string = 'goodbye', $char = 'e' Output: 'eybdoog' Input: $string = 'noitulos', $char = 's' Output: 'solution' Input: $string = 'conundrum', $char = 'z' Output: There is no 'z' in 'conundrum'
Any content of this website which has been created by Peter Campbell Smith is in the public domain