exercism-perl5

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

AtbashCipher.pm (1299B) - raw


      1 package AtbashCipher;
      2 use strict;
      3 use warnings;
      4 use Exporter qw<import>;
      5 our @EXPORT_OK = qw<encode_atbash decode_atbash>;
      6 
      7 my $ord_of_a = ord( 'a' );
      8 my $ord_of_z = ord( 'z' );
      9 my $ord_sum  = $ord_of_a + $ord_of_z;
     10 
     11 my %plain_to_cipher;
     12 my %cipher_to_plain;
     13 
     14 # initialize hashes to store encryption and decryption keys
     15 foreach ( $ord_of_a .. $ord_of_z ) {
     16     $plain_to_cipher{ chr( $_ ) } = chr( $ord_sum - $_ );
     17     $cipher_to_plain{ chr( $ord_sum - $_ ) } = chr( $_ );
     18 }
     19 
     20 sub sanitize_input {
     21     my $input = shift;
     22     $input = lc $input;         # convert to lower case
     23     $input =~ s/[^a-z0-9]//g;   # remove non letters and numbers
     24     return [ split ( //, $input ) ];
     25 }
     26 
     27 sub encode_atbash {
     28   my ($phrase) = @_;
     29   my @phrase   = @{ sanitize_input( $phrase ) };
     30   my $cipher;
     31   my $char_position = 1;
     32   foreach (@phrase) {
     33       $cipher .= ' '            # insert a space every 5 characters
     34         if ( $char_position > 1 && ($char_position - 1) % 5 == 0);
     35       my $new_char = /[0-9]/ ? $_ : $plain_to_cipher{ $_ };
     36       $cipher .= $new_char;
     37       $char_position++;
     38   }
     39   return $cipher;
     40 }
     41 
     42 sub decode_atbash {
     43   my ($phrase) = @_;
     44   my @phrase   = @{ sanitize_input( $phrase ) };
     45   my $plain;
     46   $plain .= /[0-9]/ ? $_ : $cipher_to_plain{ $_ } foreach (@phrase);
     47   return $plain;
     48 }
     49 
     50 1;