The weekly challenge 317 - Task 1: Acronyms
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-317/#TASK1 3 # 4 # Task 1: Acronyms 5 # ================ 6 # 7 # You are given an array of words and a word. 8 # 9 # Write a script to return true if concatenating the first letter of each word 10 # in the given array matches the given word, return false otherwise. 11 # 12 ## Example 1 13 ## 14 ## Input: @array = ("Perl", "Weekly", "Challenge") 15 ## $word = "PWC" 16 ## Output: true 17 # 18 # 19 ## Example 2 20 ## 21 ## Input: @array = ("Bob", "Charlie", "Joe") 22 ## $word = "BCJ" 23 ## Output: true 24 # 25 # 26 ## Example 3 27 ## 28 ## Input: @array = ("Morning", "Good") 29 ## $word = "MM" 30 ## Output: false 31 # 32 ############################################################ 33 ## 34 ## discussion 35 ## 36 ############################################################ 37 # 38 # This is actually a oneliner. We need to compare $word to 39 # the output of join("", map {substr($_,0,1)} @array) 40 # join("", ...) turns a list of strings into the concatenated 41 # string. The strings we want to concatenate are the first 42 # characters of all word in @array, which the map {...} @array 43 # part does by selecting the first character of each element via 44 # substr(). If the concatenated string is equal to $word, we 45 # can return true, otherwise false. 46 47 use v5.36; 48 49 acronyms("PWC", "Perl", "Weekly", "Challenge"); 50 acronyms("BCJ", "Bob", "Charlie", "Joe"); 51 acronyms("MM", "Morning", "Good"); 52 53 sub acronyms($word, @array) { 54 say "Input: word '$word', array (\"" . join("\", \"", @array) . "\")"; 55 if(join("", map {substr($_,0,1)} @array) eq $word) { 56 say "Output: true"; 57 } else { 58 say "Output: false"; 59 } 60 }