Advertisement
Guest User

Vigenere.pm

a guest
Nov 10th, 2013
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.50 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. sub BUILD{
  11.     my $self = shift;
  12.     my ($w, $k);
  13.     $w = $self->word;
  14.     $k = $self->key;
  15.     croak "'key' and 'word' are diferent lenght\n"
  16.         if(length $w != length $k);
  17. }
  18.  
  19. # upper case char
  20. sub toupper{ord(uc chr $_[0])}
  21. # accept only letters ACSII 65-90 and 97-122
  22. sub isalpha{chr ($_[0]) =~ /[a-zA-Z]/}
  23. # convert string to char hex ACSII
  24. sub tochar{map ord, split //, $_[0]}
  25.  
  26. has 'word' => (
  27.         is => 'rw',
  28.         isa => 'Str',
  29.         required => 1,
  30.         );
  31. has 'key' => (
  32.         is => 'rw',
  33.         isa => 'Str',
  34.         required => 1,
  35.         );
  36.  
  37.        
  38. sub encode{
  39.     my $self = shift;
  40.     my (@word, @key) = (tochar($self->word), tochar($self->key));
  41.     my ($a, $tword);
  42.     for($a = 0; $a <= @word; $a++){
  43.         if (isalpha($word[$a]) && isalpha($key[$a])){              
  44.             $word[$a] = toupper($word[$a]) - 65;
  45.             $key[$a] = toupper($key[$a]);
  46.             my $cript = $key[$a] + $word[$a];
  47.             $cript -= 26 if ($cript >= 91);
  48.             $word[$a] = $cript;
  49.             $tword .= chr $word[$a];
  50.         }
  51.     }
  52.     return $tword;
  53. }
  54.  
  55. sub decode{
  56.     my $self = shift;
  57.     my (@word, @key) = (tochar($self->word), tochar($self->key));
  58.     my ($a, $tword);
  59.     for($a = 0; $a <= @word; $a++){
  60.         if (isalpha($word[$a]) && isalpha($key[$a])){              
  61.             $word[$a] = toupper($word[$a]);
  62.             $key[$a] = toupper($key[$a]);
  63.             my $cript = $word[$a] - $key[$a] + 65;
  64.             $cript += 26 if ($cript <= 64);
  65.             $word[$a] = $cript;
  66.             $tword .= chr $word[$a];
  67.         }
  68.     }
  69.     return $tword;
  70. }
  71.  
  72. 1;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement