The weekly challenge 315 - Task 1: Find Words
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-315/#TASK1 3 # 4 # Task 1: Find Words 5 # ================== 6 # 7 # You are given a list of words and a character. 8 # 9 # Write a script to return the index of word in the list where you find the 10 # given character. 11 # 12 ## Example 1 13 ## 14 ## Input: @list = ("the", "weekly", "challenge") 15 ## $char = "e" 16 ## Output: (0, 1, 2) 17 # 18 # 19 ## Example 2 20 ## 21 ## Input: @list = ("perl", "raku", "python") 22 ## $char = "p" 23 ## Output: (0, 2) 24 # 25 # 26 ## Example 3 27 ## 28 ## Input: @list = ("abc", "def", "bbb", "bcd") 29 ## $char = "b" 30 ## Output: (0, 2, 3) 31 # 32 ############################################################ 33 ## 34 ## discussion 35 ## 36 ############################################################ 37 # 38 # This one is straight forward: For each word, check if the character 39 # is in it, at keep the index in case the character is found. 40 41 use v5.36; 42 43 find_words( ["the", "weekly", "challenge"], "e"); 44 find_words( ["perl", "raku", "python"], "p"); 45 find_words( ["abc", "def", "bbb", "bcd"], "b"); 46 47 sub find_words( $list, $char ) { 48 say "Input: \@list = (" . join("\", \"", @$list) . ", \$char = '$char'"; 49 my @list = @$list; 50 my @result = (); 51 foreach my $i (0..$#list) { 52 push @result, $i if $list[$i] =~ m/$char/; 53 } 54 say "Output: (" . join(", ", @result) . ")"; 55 }