The weekly challenge 358 - Task 2: Encrypted String
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-358/#TASK2 3 # 4 # Task 2: Encrypted String 5 # ======================== 6 # 7 # You are given a string $str and an integer $int. 8 # 9 # Write a script to encrypt the string using the algorithm - for each character 10 # $char in $str, replace $char with the $int th character after $char in the 11 # alphabet, wrapping if needed and return the encrypted string. 12 # 13 ## Example 1 14 ## 15 ## Input: $str = "abc", $int = 1 16 ## Output: "bcd" 17 # 18 # 19 ## Example 2 20 ## 21 ## Input: $str = "xyz", $int = 2 22 ## Output: "zab" 23 # 24 # 25 ## Example 3 26 ## 27 ## Input: $str = "abc", $int = 27 28 ## Output: "bcd" 29 # 30 # 31 ## Example 4 32 ## 33 ## Input: $str = "hello", $int = 5 34 ## Output: "mjqqt" 35 # 36 # 37 ## Example 5 38 ## 39 ## Input: $str = "perl", $int = 26 40 ## Output: "perl" 41 # 42 ############################################################ 43 ## 44 ## discussion 45 ## 46 ############################################################ 47 # 48 # We simply use the tr/// operator, and prepare the left and 49 # right side of that operation in two strings. That's why we 50 # need to eval the tr operation. 51 52 use v5.36; 53 54 encrypted_string("abc", 1); 55 encrypted_string("xyz", 2); 56 encrypted_string("abc", 27); 57 encrypted_string("hello", 5); 58 encrypted_string("perl", 26); 59 60 sub encrypted_string($str, $int) { 61 say "Input: \"$str\", $int"; 62 $int = $int % 26; 63 my $chars = "abcdefghijklmnopqrstuvwxyz"; 64 my $replacement = substr($chars, $int) . substr($chars, 0, $int); 65 $replacement = $chars unless $int; 66 $_ = $str; 67 eval "tr/$chars/$replacement/"; 68 say "Output: $_"; 69 }