1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-299/#TASK1 3 # 4 # Task 1: Replace Words 5 # ===================== 6 # 7 # You are given an array of words and a sentence. 8 # 9 # Write a script to replace all words in the given sentence that start with any 10 # of the words in the given array. 11 # 12 ## Example 1 13 ## 14 ## Input: @words = ("cat", "bat", "rat") 15 ## $sentence = "the cattle was rattle by the battery" 16 ## Output: "the cat was rat by the bat" 17 # 18 ## Example 2 19 ## 20 ## Input: @words = ("a", "b", "c") 21 ## $sentence = "aab aac and cac bab" 22 ## Output: "a a a c b" 23 # 24 ## Example 3 25 ## 26 ## Input: @words = ("man", "bike") 27 ## $sentence = "the manager was hit by a biker" 28 ## Output: "the man was hit by a bike" 29 # 30 ############################################################ 31 ## 32 ## discussion 33 ## 34 ############################################################ 35 # 36 # For each word in the sentence check if one of the words in the 37 # array is a prefix of the word. If that's the case, replace the 38 # word. 39 40 use strict; 41 use warnings; 42 43 replace_words( ["cat", "bat", "rat"], "the cattle was rattle by the battery" ); 44 replace_words( ["a", "b", "c"], "aab aac and cac bab" ); 45 replace_words( ["man", "bike"], "the manager was hit by a biker" ); 46 47 sub replace_words { 48 my ($words, $sentence) = @_; 49 print "Input: (" . join(", ", @$words) . "),\n"; 50 print " $sentence\n"; 51 my @s_words = split /\s+/, $sentence; 52 my @new = (); 53 foreach my $s (@s_words) { 54 foreach my $w (@$words) { 55 if($s =~ /^$w/) { 56 $s = $w; 57 last; 58 } 59 } 60 push @new, $s; 61 } 62 print "Output: " . join(" ", @new) . "\n"; 63 }