Words, words and more words
Weekly challenge 299 — 9 December 2024
Week 299: 9 Dec 2024
You are given an array of words and a sentence. Write a script to replace all words in the given sentence that start with any of the words in the given array.
Example 1 Input: @words = ("cat", "bat", "rat") $sentence = "the cattle was rattle by the battery" Output: "the cat was rat by the bat" Example 2 Input: @words = ("a", "b", "c") $sentence = "aab aac and cac bab" Output: "a a a c b" Example 3 Input: @words = ("man", "bike") $sentence = "the manager was hit by a biker" Output: "the man was hit by a bike"
Without compromising my preference for readable code I think this can be an almost-one-liner.
First we stick a space at the start of $sentence
, and then this will do it:
$sentence =~ s| $_\w+| $_|g for @words;
That says find a space followed by one of the words followed by any other letters, and replace it with just the word - and do that for each word.
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2024-12-09 use utf8; # Week 299 - task 1 - Replace words use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; replace_words(['cat', 'bat', 'rat'], 'the cattle were rattled by the battery'); replace_words(['a', 'b', 'c'], 'aab aac and cac bab'); replace_words(['six', 'three', 'four', 'one', 'five', 'two'], 'oneway twotime threesome fourfold fiver sixty'); sub replace_words { my (@words, $sentence); # initialise @words = @{$_[0]}; $sentence = ' ' . $_[1]; say qq[\nInput: \@words = ('] . join(q[', '], @words) . qq['), \$sentence = '$_[1]']; # do it and report $sentence =~ s| $_\w+| $_|g for @words; say qq[Output:$sentence]; }
Input: @words = ('cat', 'bat', 'rat'), $sentence = 'the cattle were rattled by the battery' Output: the cat were rat by the bat Input: @words = ('a', 'b', 'c'), $sentence = 'aab aac and cac bab' Output: a a a c b Input: @words = ('six', 'three', 'four', 'one', 'five', 'two'), $sentence = 'oneway twotime threesome fourfold fiver sixty' Output: one two three four five six
Any content of this website which has been created by Peter Campbell Smith is in the public domain