The weekly challenge 278 - Task 2: Reverse Word

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-278/#TASK2
 3 #
 4 # Task 2: Reverse Word
 5 # ====================
 6 #
 7 # You are given a word, $word and a character, $char.
 8 #
 9 # Write a script to replace the substring up to and including $char with its
10 # characters sorted alphabetically. If the $char doesn’t exist then DON'T do
11 # anything.
12 #
13 ## Example 1
14 ##
15 ## Input: $str = "challenge", $char = "e"
16 ## Ouput: "acehllnge"
17 #
18 ## Example 2
19 ##
20 ## Input: $str = "programming", $char = "a"
21 ## Ouput: "agoprrmming"
22 #
23 ## Example 3
24 ##
25 ## Input: $str = "champion", $char = "b"
26 ## Ouput: "champion"
27 #
28 ############################################################
29 ##
30 ## discussion
31 ##
32 ############################################################
33 #
34 # If $str matches $char, we split $str into two pieces at $char,
35 # then we split the prefix part plus $char into single characters,
36 # sort those and join them together as the new prefix to which we
37 # append the postfix part.
38 
39 use strict;
40 use warnings;
41 
42 reverse_word("challenge", "e");
43 reverse_word("programming", "a");
44 reverse_word("champion", "b");
45 
46 sub reverse_word {
47    my ($str, $char) = @_;
48    print "Input: \"$str\"\n";
49    if($str =~ m/$char/) {
50       my ($prefix, $postfix) = split /$char/, $str, 2;
51       $str = join("", sort split //, "$prefix$char") . $postfix;
52    }
53    print "Output: \"$str\"\n";
54 }