Camel
Peter
Peter Campbell Smith

Digitless Capitals

Weekly challenge 330 — 14 July 2025

Week 330: 14 Jul 2025

Task 2

Task — Title capital

You are given a string made up of one or more words separated by a single space. Write a script to capitalise the given title. If the word length is 1 or 2 then convert the word to lowercase otherwise make the first character uppercase and remaining lowercase.

Examples


Example 1
Input: $str = 'PERL IS gREAT'
Output: 'Perl is Great'

Example 2
Input: $str = 'THE weekly challenge'
Output: 'The Weekly Challenge'

Example 3
Input: $str = 'YoU ARE A stAR'
Output: 'You Are a Star'

Analysis

Another almost one line solution, though I have shown it as 3 lines to make the logic clearer. And in 30 years of writing Perl I don't think I've ever used ucfirst() before this challenge.

Note the use of \w, which matches letters in any script known to Unicode.

Try it 

Try running the script with any input:



example: it is a nice day TODAY

Script


#!/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 2 - Title capital
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';
use Encode;

title_capital('PERL IS gREAT');
title_capital('THE weekly challenge');
title_capital('YoU ARE A stAR');
title_capital('Der Nobelpreisträger Thomas Südhof spricht über eigene Fehler');

sub title_capital {
    
    my ($string, $new);
    
    # initialise
    $string = shift;
    
    # do what it says
    $new .= length($1) <= 2 ? 
        lc($1) . ' ' : 
        ucfirst(lc($1)) . ' ' 
        while $string =~ m|(\w+)|gu;
    
    # report
    $new = substr($new, 0, -1);
    say qq[\nInput:  '$string'];
    say qq[Output: '$new'];
}

Output


Input:  'PERL IS gREAT'
Output: Perl is Great

Input:  'THE weekly challenge'
Output: The Weekly Challenge

Input:  'YoU ARE A stAR'
Output: You Are a Star

Input:  'Der Nobelpreisträger Thomas Südhof spricht 
         über eigene Fehler'
Output: 'Der Nobelpreisträger Thomas Südhof Spricht 
         Über Eigene Fehler'

 

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