The weekly challenge 225 - Task 1: Max Words
1 #!/usr/bin/perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-225/#TASK1 3 # 4 # Task 1: Max Words 5 # ================= 6 # 7 # You are given a list of sentences, @list. 8 # 9 ## A sentence is a list of words that are separated by a single space with no leading or trailing spaces. 10 # 11 # 12 # Write a script to find out the maximum number of words that appear in a single sentence. 13 # 14 ## Example 1 15 ## 16 ## Input: @list = ("Perl and Raku belong to the same family.", 17 ## "I love Perl.", 18 ## "The Perl and Raku Conference.") 19 ## Output: 8 20 # 21 ## Example 2 22 ## 23 ## Input: @list = ("The Weekly Challenge.", 24 ## "Python is the most popular guest language.", 25 ## "Team PWC has over 300 members.") 26 ## Output: 7 27 # 28 ############################################################ 29 ## 30 ## discussion 31 ## 32 ############################################################ 33 # 34 # Split all sentences into their single words and count. Keep 35 # the maximum. 36 37 use strict; 38 use warnings; 39 40 max_words("Perl and Raku belong to the same family.", "I love Perl.", "The Perl and Raku Conference."); 41 max_words("The Weekly Challenge.", "Python is the most popular guest language.", "Team PWC has over 300 members."); 42 43 sub max_words { 44 my @list = @_; 45 print "Input: \@list = (\"" . join("\",\n \"",@list) . "\")\n"; 46 my $max = 0; 47 foreach my $sentence (@list) { 48 my @words = split / /, $sentence; 49 my $count = scalar(@words); 50 $max = $count if $count > $max; 51 } 52 print "Output: $max\n"; 53 } 54