The weekly challenge 253 - Task 1: Split Strings
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-253/#TASK1 3 # 4 # Task 1: Split Strings 5 # ===================== 6 # 7 # You are given an array of strings and a character separator. 8 # 9 # Write a script to return all words separated by the given character excluding 10 # empty string. 11 # 12 # Example 1 13 # 14 # Input: @words = ("one.two.three","four.five","six") 15 # $separator = "." 16 # Output: "one","two","three","four","five","six" 17 # 18 # Example 2 19 # 20 # Input: @words = ("$perl$$", "$$raku$") 21 # $separator = "$" 22 # Output: "perl","raku" 23 # 24 ############################################################ 25 ## 26 ## discussion 27 ## 28 ############################################################ 29 # 30 # This is a classic one-liner problem: join the words into a single string, 31 # then split this string into an array of strings at the separator, then 32 # only keep the non-empty strings by grepping for strings that contain one 33 # character. 34 # 35 36 use strict; 37 use warnings; 38 39 split_strings(".", "one.two.three","four.five","six"); 40 split_strings('$', '$perl$$', '$$raku$'); 41 42 sub split_strings { 43 my ($separator, @words) = @_; 44 print "Input: (\"" . join("\", \"", @words) . "\"), '$separator'\n"; 45 my @output = grep /./, split /\Q$separator\E/, join($separator, @words); 46 print "Output: (\"" . join("\", \"", @output) . "\")\n"; 47 } 48