Peter’s blog ✴ Week 315 ✴ 1 April 2025
THE WEEKLY CHALLENGE
Find answers
You are given a sentence and two words. Write a script to return all words in the given sentence that appear in sequence after the given two words.
Example 1 Input: $sentence = "Perl is a my favourite language but Python is my favourite too." $first = "my" $second = "favourite" Output: ("language", "too") Example 2 Input: $sentence = "Barbie is a beautiful doll also also a beautiful princess." $first = "a" $second = "beautiful" Output: ("doll", "princess") Example 3 Input: $sentence = "we will we will rock you rock you.", $first = "we" $second = "will" Output: ("we", "rock")
This is a simple case of matching the two words and then any third word, and doing so repeatedly.
My solution copes with punctuation and multiple spaces.
Regex in while condition is very powerful and can produce cute little one-liner. Cool, checkout and DIY.
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2025-03-31 use utf8; # Week 315 - task 2 - Find third use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; use Encode; find_third(qq[Perl is my favourite language but Python is my favourite too.], 'my', 'favourite'); find_third(qq[I like honey, I like sugar, I like everything sweet!], 'I', 'like'); find_third(qq[I like honey, I like sugar, I like everything sweet!], 'everything', 'sweet'); find_third(qq[You can include ODD SPACING], 'include', 'odd'); sub find_third { my ($sentence, $first, $second, $output); ($sentence, $first, $second) = @_; say qq[\nInput: \$sentence = '$sentence',\n \$first = '$first', \$second = '$second']; # match the two words and pick up the third $sentence =~ s|[^a-zA-Z]| |g; $output .= qq['$1', ] while $sentence =~ m|$first\s+$second\s+([a-z]+)|gi; say 'Output: ', ($output ? '(' . substr($output, 0, -2) . ')' : 'none'); }
7 lines of code
Input: $sentence = 'Perl is my favourite language but Python is my favourite too.', $first = 'my', $second = 'favourite' Output: ('language', 'too') Input: $sentence = 'I like honey, I like sugar, I like everything sweet!', $first = 'I', $second = 'like' Output: ('honey', 'sugar', 'everything') Input: $sentence = 'I like honey, I like sugar, I like everything sweet!', $first = 'everything', $second = 'sweet' Output: none Input: $sentence = 'You can include ODD SPACING', $first = 'include', $second = 'odd' Output: ('SPACING')
Any content of this website which has been created by Peter Campbell Smith is in the public domain