Peter
Peter Campbell Smith

Capital test and
ambiguous encoding

Weekly challenge 190 — 7 November 2022

Week 190 - 7 Nov 2022

Task 1

Task — Capital detection

You are given a string with alphabetic characters only: A..Z and a..z.

Write a script to find out if the usage of capitals is appropriate if it satisfies at least one of the following rules:

  1. Only first letter is capital and all others are small.
  2. Every letter is small.
  3. Every letter is capital.

Examples


Example 1
Input: $s = 'Perl'
Output: 1

Example 2
Input: $s = 'TPF'
Output: 1

Example 3
Input: $s = 'PyThon'
Output: 0

Example 4
Input: $s = 'raku'
Output: 1

Analysis

Generally I steer clear of hard-to-follow one-liners, but this one is fairly simple:

$test =~ m/^[A-Z]?([a-z]*|[A-Z]*)$/ ? 1 : 0;

In words, the string follows the rule if:

  • it starts with zero or one capital letter, and
  • it continues with either zero or more capital letters, or zero or more lower case letters.

Try it 

Try running the script with any input:



example: Challenge

Script


#!/usr/bin/perl

# Peter Campbell Smith - 2022-11-07
# PWC 190 task 1

use v5.28;
use utf8;
use warnings;
binmode(STDOUT, ':utf8');

my (@tests, $test);

@tests = qw[Perl PWC PyThon raku Byron ShakesSpeare miltoN KEATS 123 6-fold Hello! a A];

# loop over tests
 while ($test = shift @tests) {
     say qq[\nInput:  $test\nOutput: ] . ($test =~ m/^[A-Z]?([a-z]*|[A-Z]*)$/ ? 1 : 0);
}

Output


Input:  Perl
Output: 1

Input:  PWC
Output: 1

Input:  PyThon
Output: 0

Input:  raku
Output: 1

Input:  Byron
Output: 1

Input:  ShakesSpeare
Output: 0

Input:  miltoN
Output: 0

Input:  KEATS
Output: 1

Input:  123
Output: 0

Input:  6-fold
Output: 0

Input:  Hello!
Output: 0

Input:  a
Output: 1

Input:  A
Output: 1

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