Advertisement
Guest User

Vigenere.pm

a guest
Nov 10th, 2013
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.80 KB | None | 0 0
  1. use common::sense;
  2.  
  3. package Vigenere;
  4.  
  5. use Moose;
  6. use autobox::Core;
  7. use Carp 'croak';
  8. use lib 'Strings';
  9.  
  10. # upper case char
  11. sub toupper{ord(uc chr $_[0])}
  12. # accept only letters ACSII 65-90 and 97-122
  13. sub isalpha{chr($_[0]) =~ /[a-zA-Z]/}
  14. # convert string to char hex ACSII
  15. sub tochar{map ord, split //, $_[0]}
  16.  
  17. has 'word' =>(
  18.         is => 'rw',
  19.         isa => 'Str',
  20.         default => sub { croak "Invalid argument type 'word'";}
  21.         );
  22. has 'key' =>(
  23.         is => 'rw',
  24.         isa => 'Str',
  25.         default => sub { croak "Invalid argument type 'key'";}
  26.         );
  27.        
  28.        
  29. #has 'opt' =>(
  30. #       is => 'rw',
  31. #       isa => 'str',
  32. #       default => sub {'e'}
  33. #       );
  34. #
  35. #sub op{
  36. #   my $self = shift;
  37. #   encode($self->word, $self->key) if ($self->opt eq 'e');
  38. #   decode($self->word, $self->key) if ($self->opt eq 'd');
  39. #}
  40.        
  41. sub encode{
  42.     my $self = shift;
  43.     my (@word, @key) = (tochar($self->word), tochar($self->key));
  44.     my ($a, $tword);
  45.     croak "'key' and 'word' are diferent lenght\n"
  46.             unless ($#word == $#key);
  47.     for($a = 0; $a <= @word; $a++){
  48.         if (isalpha($word[$a]), isalpha($key[$a])){            
  49.             $word[$a] = toupper($word[$a]) - 65;
  50.             $key[$a] = toupper($key[$a]);
  51.             my $cript = $key[$a] + $word[$a];
  52.             $cript -= 26 if ($cript >= 91);
  53.             $word[$a] = $cript;
  54.             $tword .= chr $word[$a];
  55.         }
  56.     }
  57.     return $tword;
  58. }
  59.  
  60. sub decode{
  61.     my $self = shift;
  62.     my (@word, @key) = (tochar($self->word), tochar($self->key));
  63.     my ($a, $tword);
  64.     croak "'key' and 'word' are diferent lenght\n"
  65.             unless ($#word == $#key);
  66.     for($a = 0; $a <= @word; $a++){
  67.         if (isalpha($word[$a]), isalpha($key[$a])){            
  68.             $word[$a] = toupper($word[$a]);
  69.             $key[$a] = toupper($key[$a]);
  70.             my $cript = $word[$a] - $key[$a] + 65;
  71.             $cript += 26 if ($cript <= 64);
  72.             $word[$a] = $cript;
  73.             $tword .= chr $word[$a];
  74.         }
  75.     }
  76.     return $tword;
  77. }
  78.  
  79. 1;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement