perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 330 - Task 2: Title Capital

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-330/#TASK2
 3 #
 4 # Task 2: Title Capital
 5 # =====================
 6 #
 7 # You are given a string made up of one or more words separated by a single
 8 # space.
 9 #
10 # Write a script to capitalise the given title. If the word length is 1 or 2
11 # then convert the word to lowercase otherwise make the first character
12 # uppercase and remaining lowercase.
13 #
14 ## Example 1
15 ##
16 ## Input: $str = "PERL IS gREAT"
17 ## Output: "Perl is Great"
18 #
19 #
20 ## Example 2
21 ##
22 ## Input: $str = "THE weekly challenge"
23 ## Output: "The Weekly Challenge"
24 #
25 #
26 ## Example 3
27 ##
28 ## Input: $str = "YoU ARE A stAR"
29 ## Output: "You Are a Star"
30 #
31 ############################################################
32 ##
33 ## discussion
34 ##
35 ############################################################
36 #
37 # We split the input into the individual words. Then we lowercase all words of
38 # a length <= 2. For the words longer than that, we uppercase the first
39 # character and lowercase the rest. In the end, we join the words together
40 # again to form the full sentence.
41 
42 use v5.36;
43 
44 title_capital("PERL IS gREAT");
45 title_capital("THE weekly challenge");
46 title_capital("YoU ARE A stAR");
47 
48 sub title_capital($str) {
49     say "Input: \"$str\"";
50     my @output = ();
51     my @words = split /\s+/, $str;
52     foreach my $word (@words) {
53         if(length($word) <= 2) {
54             push @output, lc($word);
55         } else {
56             push @output, uc(substr($word,0,1)) . lc(substr($word,1));
57         }
58     }
59     say "Output: " . join(" ", @output);
60 }