#!/usr/local/bin/perl6 # Perl 6 version of the Vigenere cipher. # Rougly based on the Perl 5 CPAN module Crypt::Vigenere. class Vigenere:auth:ver<1.0.1> { has $.keyword; has @!fwdLookupTable; has @!revLookupTable; method !initTable { for $.keyword.lc.comb { my $def = "a" => "a"; ## Used in case of 'a'. my $ks = (ord($_)-97) % 26; my $ke = $ks - 1; if $ke < 0 { ## A is A @!fwdLookupTable.push: $def; @!revLookupTable.push: $def; next; } my $s = chr(ord('a') + $ks); my $e = chr(ord('a') + $ke); my $ls = "a..z"; my $le = "$s..za..$e"; @!fwdLookupTable.push: $ls => $le; @!revLookupTable.push: $le => $ls; } } method encodeMessage ($string) { self!initTable if !@!fwdLookupTable; return self!doTheMath($string, @!fwdLookupTable); } method decodeMessage ($string) { self!initTable if !@!revLookupTable; return self!doTheMath($string, @!revLookupTable); } method !doTheMath ($string, @lookupTable) { my $returnString; my $count = 0; for $string.lc.comb { if // { $_.=trans(@lookupTable[$count % $.keyword.chars]); $count++; } $returnString ~= $_; } return $returnString; } } if @*ARGS.elems < 3 { .say for 'usage: ./vigenere.pl [a bunch of text]', '', 'Modes:', ' -e Encode using passphrase. Display output in lowercase.', ' -E Encode using passphrase. Display output in UPPERCASE.', ' -d Decode using passphrase. Display output in lowercase.', ' -D Decode using passphrase. Display output in UPPERCASE.', ''; exit; } my $mode = @*ARGS.shift; my $cipher = Vigenere.new(keyword => @*ARGS.shift); my $message; given $mode { when /<[dD]>/ { $message = $cipher.decodeMessage(@*ARGS.join(' ')); } default { $message = $cipher.encodeMessage(@*ARGS.join(' ')); } } if $mode.match(/<[A..Z]>/) { $message.=uc; } say $message;