perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 341 - Task 2: Reverse Prefix

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-341/#TASK2
 3 #
 4 # Task 2: Reverse Prefix
 5 # ======================
 6 #
 7 # You are given a string, $str and a character in the given string, $char.
 8 #
 9 # Write a script to reverse the prefix upto the first occurrence of the given
10 # $char in the given string $str and return the new string.
11 #
12 ## Example 1
13 ##
14 ## Input: $str = "programming", $char = "g"
15 ## Output: "gorpramming"
16 ##
17 ## Reverse of prefix "prog" is "gorp".
18 #
19 #
20 ## Example 2
21 ##
22 ## Input: $str = "hello", $char = "h"
23 ## Output: "hello"
24 #
25 #
26 ## Example 3
27 ##
28 ## Input: $str = "abcdefghij", $char = "h"
29 ## Output: "hgfedcbaij"
30 #
31 #
32 ## Example 4
33 ##
34 ## Input: $str = "reverse", $char = "s"
35 ## Output: "srevere"
36 #
37 #
38 ## Example 5
39 ##
40 ## Input: $str = "perl", $char = "r"
41 ## Output: "repl"
42 #
43 ############################################################
44 ##
45 ## discussion
46 ##
47 ############################################################
48 #
49 # This is a simple s/old/new/ thanks to perl's s///e feature.
50 # We just need a regular expression that collects everything from
51 # the beginning of the string up until the first appearance of $char.
52 # The rest is applying reverse() to it which does exactly what we
53 # need in scalar context.
54 
55 use v5.36;
56 
57 reverse_prefix("programming", "g");
58 reverse_prefix("hello", "h");
59 reverse_prefix("abcdefghij", "h");
60 reverse_prefix("reverse", "s");
61 reverse_prefix("perl", "r");
62 
63 sub reverse_prefix($str, $char) {
64     say "Input: '$str', '$char'";
65     $str =~ s/^([^$char]*$char)/reverse($1)/e;
66     say "Output: $str";
67 }