TASK #1: Max Words
You are given an array of sentences.
Write a script to return the maximum number of words that appear in a single sentence.
#!/usr/bin/perl use strict; use warnings; use List::Util qw(max); sub max_words { # This line finds the maximum number of words in any sentence passed to the # function. The first argument is expected to be an array reference, which is # dereferenced to obtain the list of sentences. Each sentence is split on # whitespace to produce a list of words, `scalar` forces the count of those # words, `map` collects the word counts for all sentences, and `max` returns # the largest of those counts. die "An array reference expected!\n" unless ref($_[0]) eq 'ARRAY'; return max( map { scalar (split /\s+/, $_) } @{ $_[0] } ); } # Alternative with simple for loop sub max_words_alt { my ($sentences) = @_; die "An array reference expected!\n" unless ref($sentences) eq 'ARRAY'; my $max = 0; for my $sentence (@$sentences) { my $count = scalar (split /\s+/, $sentence); $max = $count if ($count > $max); } return $max; } # Tests my @sentences; @sentences = ("Hello world", "This is a test", "Perl is great"); printf "%d\n", max_words(\@sentences); # 4 printf "%d\n", max_words_alt(\@sentences); # 4 @sentences = ("Single"); printf "%d\n", max_words(\@sentences); # 1 printf "%d\n", max_words_alt(\@sentences); # 1 @sentences = ("Short", "This sentence has six words in total", "A B C", "Just four words here"); printf "%d\n", max_words(\@sentences); # 7 printf "%d\n", max_words_alt(\@sentences); # 7 @sentences = ("One", "Two parts", "Three part phrase", ""); printf "%d\n", max_words(\@sentences); #3 printf "%d\n", max_words_alt(\@sentences); #3 @sentences = ("The quick brown fox jumps over the lazy dog", "A", "She sells seashells by the seashore", "To be or not to be that is the question"); printf "%d\n", max_words(\@sentences); #10 printf "%d\n", max_words_alt(\@sentences); #10