perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 369 - Task 1: Valid Tag

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-369/#TASK1
 3 #
 4 # Task 1: Valid Tag
 5 # =================
 6 #
 7 # You are given a given a string caption for a video.
 8 #
 9 # Write a script to generate tag for the given string caption in three steps as
10 # mentioned below:
11 #
12 # 1. Format as camelCase
13 # Starting with a lower-case letter and capitalising the first letter of each
14 # subsequent word. Merge all words in the caption into a single string
15 # starting with a #.
16 # 2. Sanitise the String
17 # Strip out all characters that are not English letters (a-z or A-Z).
18 # 3. Enforce Length
19 # If the resulting string exceeds 100 characters, truncate it so it is
20 # exactly 100 characters long.
21 #
22 ## Example 1
23 ##
24 ## Input: $caption = "Cooking with 5 ingredients!"
25 ## Output: "#cookingWithIngredients"
26 #
27 ## Example 2
28 ##
29 ## Input: $caption = "the-last-of-the-mohicans"
30 ## Output: "#thelastofthemohicans"
31 #
32 ## Example 3
33 ##
34 ## Input: $caption = "  extra spaces here"
35 ## Output: "#extraSpacesHere"
36 #
37 ## Example 4
38 ##
39 ## Input: $caption = "iPhone 15 Pro Max Review"
40 ## Output: "#iphoneProMaxReview"
41 #
42 ## Example 5
43 ##
44 ## Input: $caption = "Ultimate 24-Hour Challenge: Living in a Smart Home controlled entirely by Artificial Intelligence and Voice Commands in the year 2026!"
45 ## Output: "#ultimateHourChallengeLivingInASmartHomeControlledEntirelyByArtificialIntelligenceAndVoiceCommandsIn"
46 #
47 ############################################################
48 ##
49 ## discussion
50 ##
51 ############################################################
52 #
53 # After removing any non-word characters before the first a-z/A-Z, we just need
54 # to split $caption into individual words, lowercase each one, and uppercase
55 # the first character starting at the second word. In the end, we prepend a
56 # single "#" and limit the length to 99 characters from the result string we
57 # created before that.
58 
59 use v5.36;
60 
61 valid_tag("Cooking with 5 ingredients!");
62 valid_tag("the-last-of-the-mohicans");
63 valid_tag("  extra spaces here");
64 valid_tag("iPhone 15 Pro Max Review");
65 valid_tag("Ultimate 24-Hour Challenge: Living in a Smart Home controlled entirely by Artificial Intelligence and Voice Commands in the year 2026!");
66 
67 sub valid_tag($caption) {
68     say "Input: \"$caption\"";
69     $caption =~ s/^[^A-Za-z]+//;
70     my @words = split /\s+/, $caption;
71     my $result = shift @words;
72     $result =~ s/[^a-zA-Z]//g;
73     $result = lc($result);
74     foreach my $word (@words) {
75         $word =~ s/[^a-zA-Z]//g;
76         $word = lc($word);
77         $word =~ s/^[a-z]/uc($&)/e;
78         $result .= $word;
79     }
80     $result = "#" . substr($result,0,99);
81     say "Output: \"$result\"";
82 }