Camel
Peter
Peter Campbell Smith

gROUP dIGIT sUM

Weekly challenge 311 — 3 March 2025

Week 311: 3 Mar 2025

Task 1

Task — Upper lower

You are given a string consisting of english letters only. Write a script to convert lower case to upper and upper case to lower in the given string.

Examples


Example 1
Input: $str = "pERl"
Output: "PerL"

Example 2
Input: $str = "rakU"
Output: "RAKu"

Example 3
Input: $str = "PyThOn"
Output: "pYtHoN"

Analysis

This challenge can be solved in a single line of what I believe to be easily understandable code, and that's what I've submitted.

But I am uneasy.

Firstly, in real life I would never accept the assertion that the input is what it says it is. In this case I would check that the string does indeed consist of only upper and lower case letters in the Latin alphabet, and either raise an error, or make some documented correction - for example replacing non-letters with '?'.

Secondly, my solution assumes that upper and lower case letters are represented internally by integers which differ by 32 - so for example 'A' is 65 and 'a' is 97. That's true in ASCII and Unicode, but not in - for example - EBCDIC, where 'A' is 193 and 'a' is 129. And while in EBCDIC there is a constant difference between the corresponding upper and lower case letters, that might not be true in every encoding.

You might also be surprised to know that in EBCDIC - still used widely in IBM and similar products that ord('J') - ord('I') is 8.

There are, of course, ways to solve the challenge that do not require an assumption about encoding and in general I make it a rule in production code to avoid - if possible - relying on any specific character encoding.

Try it 

Try running the script with any input:



example: LOWERupper

Script


#!/usr/bin/perl

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

use v5.26;    # The Weekly Challenge - 2025-03-03
use utf8;     # Week 311 - task 1 - Upper lower
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';

upper_lower('abcdeABCDE');
upper_lower('TheQuickBrownFoxJumpsOverTheLazyDog');

sub upper_lower {
    
    my ($sTrInG, $StRiNg);
    
    $sTrInG = shift @_;
    
    # add 32 to upper case, subtract 32 from lower
    $StRiNg .= ($_ gt 'Z' ? chr(ord($_) - 32) : 
       chr(ord($_) + 32)) for split('', $sTrInG);
    
    say qq[\nInput:  \$string = $sTrInG];
    say qq[Output:           $StRiNg];
}

Output


Input:  $string = abcdeABCDE
Output:           ABCDEabcde

Input:  $string = TheQuickBrownFoxJumpsOverTheLazyDog
Output:           tHEqUICKbROWNfOXjUMPSoVERtHElAZYdOG

 

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