The weekly challenge 379 - Task 1: Reverse String
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-379/#TASK1 3 # 4 # Task 1: Reverse String 5 # ====================== 6 # 7 # You are given a string. 8 # 9 # Write a script to reverse the given string without using standard reverse 10 # function. 11 # 12 ## Example 1 13 ## 14 ## Input: $str = "" 15 ## Output: "" 16 # 17 ## Example 2 18 ## 19 ## Input: $str = "reverse the given string" 20 ## Output: "gnirts nevig eht esrever" 21 # 22 ## Example 3 23 ## 24 ## Input: $str = "Perl is Awesome" 25 ## Output: "emosewA si lreP" 26 # 27 ## Example 4 28 ## 29 ## Input: $str = "v1.0.0-Beta!" 30 ## Output: "!ateB-0.0.1v" 31 # 32 ## Example 5 33 ## 34 ## Input: $str = "racecar" 35 ## Output: "racecar" 36 # 37 ############################################################ 38 ## 39 ## discussion 40 ## 41 ############################################################ 42 # 43 # Since we can't use reverse(), we just cut the first character as 44 # long as the string still has characters, and put it in front of 45 # the result string. 46 47 use v5.36; 48 49 reverse_string(""); 50 reverse_string("reverse the given string"); 51 reverse_string("Perl is Awesome"); 52 reverse_string("v1.0.0-Beta!"); 53 reverse_string("racecar"); 54 55 sub reverse_string($str) { 56 say "Input: \"$str\""; 57 my $result = ""; 58 while(length($str) > 0) { 59 $str =~ s/(.)//; 60 $result = $1 . $result; 61 } 62 say "Output: \"$result\""; 63 }