Peter’s blog ✴ Week 278 ✴ 15 July 2024

THE WEEKLY CHALLENGE
Tangled string and drow

The Perl Camel

Task 2

Reverse word

You are given a word, $word and a character, $char. Write a script to replace the substring up to and including $char with its characters sorted alphabetically. If the $char doesn’t exist in the word then don’t do anything.

Examples


Example 1
Input: $str = "challenge", $char = "e"
Output: "acehllnge"

Example 2
Input: $str = "programming", $char = "a"
Output: "agoprrmming"

Example 3
Input: $str = "champion", $char = "b"
Output: "champion"

Analysis

This could easily be a one-line answer by using an $a ? $b : $c construct, but for ease of understanding I've used if ($a) { $b } else { $c }.

Perl Weekly’s review

from PW issue 678

DIY web interface with detailed analysis. Cool quality solutions every week.

This review may cover either or both challenges for this week.

Try it 

Try running the script with any input:



example: mushroom



example: r

Script


#!/usr/bin/perl

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

use v5.26;    # The Weekly Challenge - 2024-07-15
use utf8;     # Week 278 - task 2 - Reverse word
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';

reverse_word('challenge', 'e');
reverse_word('programming', 'a');
reverse_word('champion', 'b');
reverse_word('testing', 't');
reverse_word('multiplication', 'n');

sub reverse_word {
    
    my ($word, $char, $output);
    
    ($word, $char) = @_;
    if ($word =~ m|(.*?$char)(.*)|) {
        $output = join('', sort(split(//, $1))) . $2;
    } else {
        $output = $word;
    }
    
    printf(qq[\nInput:  \$word = '%s', \$char = '%s'\n], $word, $char);
    printf(qq[Output: '%s'\n], $output);
}

9 lines of code

Output from script


Input:  $word = 'challenge', $char = 'e'
Output: 'acehllnge'

Input:  $word = 'programming', $char = 'a'
Output: 'agoprrmming'

Input:  $word = 'champion', $char = 'b'
Output: 'champion'

Input:  $word = 'testing', $char = 't'
Output: 'testing'

Input:  $word = 'multiplication', $char = 'n'
Output: 'aciiillmnopttu'

 

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