exercism-perl5

Repository for my Perl 5 Exercism exercises
git clone git://git.samirparikh.com/exercism-perl5
Log | Files | Refs | README

commit 84cd503deaa22246c87f796d5753dfa916891336
parent 1a7458d1535b3d8b08202c95eda9afac26d1acbb
Author: Samir Parikh <noreply@samirparikh.com>
Date:   Fri, 28 Jan 2022 19:35:59 +0000

finish encoding subroutine

Diffstat:
Matbash-cipher/AtbashCipher.pm | 18++++++++++++++++--
1 file changed, 16 insertions(+), 2 deletions(-)

diff --git a/atbash-cipher/AtbashCipher.pm b/atbash-cipher/AtbashCipher.pm @@ -11,17 +11,31 @@ my $ord_sum = $ord_of_a + $ord_of_z; my %plain_to_cipher; my %cipher_to_plain; +# initialize hashes to store encryption and decryption keys foreach ( $ord_of_a .. $ord_of_z ) { $plain_to_cipher{ chr( $_ ) } = chr( $ord_sum - $_ ); $cipher_to_plain{ chr( $ord_sum - $_ ) } = chr( $_ ); } +sub sanitize_input { + my $input = shift; + $input = lc $input; # convert to lower case + $input =~ s/[^a-z0-9]//g; # remove non letters and numbers + return [ split ( //, $input ) ]; +} + sub encode_atbash { my ($phrase) = @_; - my @phrase = split //, lc $phrase; + my @phrase = @{ sanitize_input( $phrase ) }; my $cipher; + my $char_position = 1; foreach (@phrase) { - $cipher .= $plain_to_cipher{ $_ }; + # insert a space every 5 characters + $cipher .= ' ' + if ( $char_position > 1 && ($char_position - 1) % 5 == 0); + my $new_char = /[0-9]/ ? $_ : $plain_to_cipher{ $_ }; + $cipher .= $new_char; + $char_position++; } return $cipher; }