Peter’s blog ✴ Week 240 ✴ 23 October 2023

THE WEEKLY CHALLENGE
Initialisms and contorted arrays

The Perl Camel

Task 1

Acronym

You are given an array of strings and a check string. Write a script to find out if the check string is the acronym of the words in the given array.

Examples


Example 1
Input: @str = ("Perl", "Python", "Pascal")
       $chk = "ppp"
Output: true

Example 2
Input: @str = ("Perl", "Raku")
       $chk = "rp"
Output: false

Example 3
Input: @str = ("Oracle", "Awk", "C")
       $chk = "oac"
Output: true

Analysis

All that's needed here is to concatenate the initial letters of @str and compare the result with $chk:

$initials .= lc(substr($_, 0, 1)) for @str;
$result = $initials eq lc($chk) ? 'true' : 'false';

I am sorry that the 'Try it' feature is currently working very slowly or not at all owing to some issue with my web hosting provider.

Try it 

Try running the script with any input:



example: Pink, elephants, run, loose



example: Perl

Script


#!/usr/bin/perl

use v5.16;    # The Weekly Challenge - 2023-10-23
use utf8;     # Week 240 task 1 - Acronym
use strict;   # Peter Campbell Smith
use warnings; # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

acronym(['Perl', 'Python', 'Pascal'], 'ppp');
acronym(['hyper', 'text', 'markup', 'language'], 'HTML');
acronym(['All', 'clients', 'receive', 'our', 'New', 'Year', 'message'], 'acronym');
acronym(['Once', 'upon', 'a', 'time'], 'tauo');

sub acronym {
    
    my (@str, $chk, $initials);
    
    # initialise
    @str = @{$_[0]};
    $chk = $_[1];
    
    # concatenate first letters of @str
    $initials = '';
    $initials .= lc(substr($_, 0, 1)) for @str;
    
    # show results
    say qq[\nInput:  \@str = ('] . join(q[', '], @str) . q[')];
    say qq[        \$chk = '$chk'];
    say qq[Output: ] . ($initials eq lc($chk) ? 'true' : 'false');
}
    

9 lines of code

Output from script


Input:  @str = ('Perl', 'Python', 'Pascal')
        $chk = 'ppp'
Output: true

Input:  @str = ('hyper', 'text', 'markup', 'language')
        $chk = 'HTML'
Output: true

Input:  @str = ('All', 'clients', 'receive', 'our', 'New', 'Year', 'message')
        $chk = 'acronym'
Output: true

Input:  @str = ('Once', 'upon', 'a', 'time')
        $chk = 'tauo'
Output: false

 

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