Peter’s blog ✴ Week 392 ✴ 21 September 2026

THE WEEKLY CHALLENGE
Palindromes and products

The Perl Camel

Task 1

Convert palindrome

You are given a $string. Write a script to convert the given $string to be a palindrome by adding characters in front of it.

Examples


Example 1
Input: $str = 'pinnipeds'
Output: 'sdepinnipeds'

Example 2
Input: $str = 'abcd'
Output: 'dcbabcd'

Example 3
Input: $str = 'bananas'
Output: 'sananabananas'

Example 4
Input: $str = 'dissident'
Output: 'tnedissident'

Example 5
Input: $str = 'cailliachs'
Output: 'shcailliachs'

Analysis

Clearly the way to do this is to look for the longest $substring which starts at the beginning of $string and is palindromic.

The solution is then reverse($substring) . $string.

$substring will not be an empty string, because the first letter of $string on its own is a palindrome, at least in the sense of $string eq reverse($string).

That also means that the length of $substring will also never equal that of $string.

So there are no edge cases to be handled, which is useful.

Execution time is also hardly relevant, but for the record, my solution only calls reverse once to reverse the whole $string rather than continually reversing substrings.

Try it 

Your input:



eg: anaphylactic

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use v5.26;    # The Weekly Challenge - 2026-09-21
use utf8;     # Week 392 - task 1 - Convert palindrome
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';
use Encode;

convert_palindrome('pinnipeds');
convert_palindrome('palindrome');
convert_palindrome('bananas');
convert_palindrome('dissident');
convert_palindrome('detartrated');

sub convert_palindrome {
    
    my ($string, $gnirts, $s, $j);
    
    # initialise
    $string = shift;
    $gnirts = reverse($string);
    $s = length($string);
    
    # seek matching substring
    for ($j = $s; $j > 0; $j --) {
        last if substr($string, 0, $j) eq substr($gnirts, -$j);
    }
    
    # report
    say qq[\nInput:  '$string'];
    say qq[Output: '] . substr($gnirts, 0, $s - $j) . $string . q['];
}

9 lines of code

Output from script


Input:  'pinnipeds'
Output: 'sdepinnipeds'

Input:  'palindrome'
Output: 'emordnilapalindrome'

Input:  'bananas'
Output: 'sananabananas'

Input:  'dissident'
Output: 'tnedissident'

Input:  'detartrated'
Output: 'detartrated'

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain