Peter’s blog ✴ Week 341 ✴ 29 September 2025

THE WEEKLY CHALLENGE
Broken keys and mixed up words

The Perl Camel

Task 2

Reverse prefix

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.

Examples


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'

Analysis

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.

Perl Weekly’s review

from Perl Weekly issue 741

This is a practical, well-documented technical blog post that demonstrates a regex-focused approach to problem-solving with strong emphasis on robustness and error handling. Peter provides clean, working solutions with comprehensive examples and thoughtful edge case consideration.

Try it 

Try running the script with any input:



example: metpesber



example: s

Script


#!/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];
}

9 lines of code

Output from script


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