The weekly challenge 256 - Task 2: Merge Strings
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-256/#TASK2 3 # 4 # Task 2: Merge Strings 5 # ===================== 6 # 7 # You are given two strings, $str1 and $str2. 8 # 9 # Write a script to merge the given strings by adding in alternative order 10 # starting with the first string. If a string is longer than the other then 11 # append the remaining at the end. 12 # 13 ## Example 1 14 ## 15 ## Input: $str1 = "abcd", $str2 = "1234" 16 ## Output: "a1b2c3d4" 17 # 18 ## Example 2 19 ## 20 ## Input: $str1 = "abc", $str2 = "12345" 21 ## Output: "a1b2c345" 22 # 23 ## Example 3 24 ## 25 ## Input: $str1 = "abcde", $str2 = "123" 26 ## Output: "a1b2c3de" 27 # 28 ############################################################ 29 ## 30 ## discussion 31 ## 32 ############################################################ 33 # 34 # Turn both strings into arrays, get elements from both arrays 35 # until the first one is empty, then add the remainder of the 36 # second one. 37 38 use strict; 39 use warnings; 40 41 merge_strings("abcd", "1234"); 42 merge_strings("abc", "12345"); 43 merge_strings("abcde", "123"); 44 45 sub merge_strings { 46 my ($str1, $str2) = @_; 47 print "Input: str1 = \"$str1\", str2 = \"$str2\"\n"; 48 my $output = ""; 49 my @first = split //, $str1; 50 my @second = split //, $str2; 51 while (my $c = shift @first) { 52 $output .= $c; 53 $output .= shift @second // ""; 54 } 55 $output .= join("", @second); 56 print "Output: \"$output\"\n"; 57 }