Peter’s blog ✴ Week 331 ✴ 21 July 2025
THE WEEKLY CHALLENGE
Last word, buddy
You are given a string. Write a script to find the length of the last word in the given string.
Example 1 Input: $str = 'The Weekly Challenge' Output: 9 Example 2 Input: $str = ' Hello World ' Output: 5 Example 3 Input: $str = 'Let's begin the fun' Output: 3
Well, this isn't too hard. We're looking for a string of letters, followed by 0 or more non-letters and the end of the string, which is easy to say in regular-expressionese.
The only slight edge case is when there are no words at all in the string.
The post is practical, well-structured and thoughtful. It balances clarity with technical depth, making it useful for readers who want both an understanding of the problem and insight into efficient approaches.
This review may cover either or both challenges for this week.
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.
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2025-07-21 use utf8; # Week 331 - task 1 - Last word use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; use Encode; last_word('The Weekly Challenge'); last_word(' Hello World '); last_word('123 4567'); last_word(''); last_word('Danger!'); sub last_word { $_[0] =~ m|([a-z]+)[^a-z]*$|i; say qq[\nInput: '$_[0]']; say qq[Output: ] . (defined($1) ? length($1) : 0); }
4 lines of code
Input: 'The Weekly Challenge' Output: 9 Input: ' Hello World ' Output: 5 Input: '123 4567' Output: 0 Input: '' Output: 0 Input: 'Danger!' Output: 6
Any content of this website which has been created by Peter Campbell Smith is in the public domain