The weekly challenge 230 - Task 2: Count Words

 1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-230/#TASK2
 3 #
 4 # Task 2: Count Words
 5 # ===================
 6 #
 7 # You are given an array of words made up of alphabetic characters and a prefix.
 8 #
 9 # Write a script to return the count of words that starts with the given prefix.
10 #
11 ## Example 1
12 ##
13 ## Input: @words  = ("pay", "attention", "practice", "attend")
14 ##        $prefix = "at"
15 ## Ouput: 2
16 ##
17 ## Two words "attention" and "attend" starts with the given prefix "at".
18 #
19 ## Example 2
20 ##
21 ## Input: @words  = ("janet", "julia", "java", "javascript")
22 ##        $prefix = "ja"
23 ## Ouput: 3
24 ##
25 ## Three words "janet", "java" and "javascripr" starts with the given prefix "ja".
26 #
27 ############################################################
28 ##
29 ## discussion
30 ##
31 ############################################################
32 #
33 # Go word by word, increment a counter if the word starts with
34 # the prefix.
35 use strict;
36 use warnings;
37 
38 count_words("at", "pay", "attention", "practice", "attend");
39 count_words("ja", "janet", "julia", "java", "javascript");
40 
41 sub count_words {
42    my ($prefix, @words) = @_;
43    my $count = 0;
44    print "Input: \@words = (" . join(", ", @words) . "), \$prefix = $prefix\n";
45    foreach my $word (@words) {
46       $count++ if $word =~ m/^$prefix/;
47    }
48    print "Output: $count\n";
49 }