Peter’s blog ✴ Week 319 ✴ 28 April 2025

THE WEEKLY CHALLENGE
Vowels and minima

The Perl Camel

Task 1

Word count

You are given a list of words containing alphabetic characters only. Write a script to return the count of words either starting with a vowel or ending with a vowel.

Examples


Example 1
Input: @list = ('unicode', 'xml', 'raku', 'perl')
Output: 2
The words are 'unicode' and 'raku'.

Example 2
Input: @list = ('the', 'weekly', 'challenge')
Output: 2

Example 3
Input: @list = ('perl', 'python', 'postgres')
Output: 0

Analysis

This is another challenge where the choice is between a one-liner with a single regular expression or a more verbose version which is easier for someone to maintain when I am not around. As usual, I have gone for the second option.

I have handled the 'starting' and 'ending' cases with separate regular expressions but taken care that that does not result in a count of 2 when a word both starts and ends with a vowel. There are also a few slightly edgy cases such as 'a' or 'I'.

So not a very challenging challenge, but still one that has some scope for serious thought.

Perl Weekly’s review

from PW issue 719

Nice to see the test goes beyond the example and dealing with extreme use case. And don't forget the DIY tool. Keep it up great work.

Try it 

Try running the script with any input:



example: The curfew tolls the knell of parting day

Script


#!/usr/bin/perl

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

use v5.26;    # The Weekly Challenge - 2025-04-28
use utf8;     # Week 319 - task 1 - Word count
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';
use Encode;

word_count('unicode', 'xml', 'raku', 'perl');
word_count('carrot', 'pear', 'cauliflower', 'turnip');
word_count('a', 'ee', 'iii', 'oooo', 'uuuuu');

sub word_count {
    
    my (@words, $w, $count, $result);
    
    # count words starting or ending with a vowel
    for $w (@_) {
        next unless ($w =~ m|^[aeiou]i| or $w =~ m|[aeiou]$|i);
        $result .= qq['$w', ];
        $count ++;
    }
    
    say qq[\nInput:  ('] . join(q[', '], @_) . q[')];
    say qq[Output: ] . ($count ? qq[$count - ] . substr($result, 0, -2) : '0');
}

8 lines of code

Output from script


Input:  ('unicode', 'xml', 'raku', 'perl')
Output: 2 - 'unicode', 'raku'

Input:  ('carrot', 'pear', 'cauliflower', 'turnip')
Output: 0

Input:  ('a', 'ee', 'iii', 'oooo', 'uuuuu')
Output: 5 - 'a', 'ee', 'iii', 'oooo', 'uuuuu'

 

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