2015-12-11 10:35:30 -08:00
|
|
|
package DDG::Goodie::CaesarCipher;
|
|
|
|
# ABSTRACT: Perform a simple Caesar cipher on some text.
|
|
|
|
|
|
|
|
use strict;
|
|
|
|
use DDG::Goodie;
|
|
|
|
|
|
|
|
triggers start => "caesar cipher", "caesar",
|
2015-12-12 02:05:18 -08:00
|
|
|
"ceasar", "ceasar cipher",
|
|
|
|
"shift cipher";
|
2015-12-11 10:35:30 -08:00
|
|
|
|
|
|
|
zci is_cached => 1;
|
|
|
|
zci answer_type => "caesar_cipher";
|
|
|
|
|
2015-12-12 02:41:15 -08:00
|
|
|
my @alphabet = ('a' ... 'z');
|
|
|
|
|
|
|
|
my $string_alphabet = join '', @alphabet;
|
|
|
|
|
2015-12-11 10:36:10 -08:00
|
|
|
handle remainder => sub {
|
|
|
|
return unless $_ =~ /(\-?\d+)\s+([[:ascii:]]+)$/;
|
|
|
|
my ($shift_val, $to_cipher) = ($1, $2);
|
|
|
|
|
|
|
|
my $amount = $shift_val % 26;
|
2015-12-12 02:41:15 -08:00
|
|
|
# This creates the cipher by shifting the alphabet.
|
|
|
|
my @shifted_alphabet = (@alphabet[$amount...25],
|
|
|
|
@alphabet[0..$amount-1]);
|
2015-12-11 10:36:10 -08:00
|
|
|
my $result;
|
|
|
|
foreach my $char (split //, $to_cipher) {
|
|
|
|
if ($char =~ /[[:alpha:]]/) {
|
|
|
|
my $uppercase = $char =~ /[A-Z]/;
|
2015-12-12 02:41:15 -08:00
|
|
|
my $idx = index $string_alphabet, lc $char;
|
|
|
|
$char = $shifted_alphabet[$idx] if ($idx != -1);
|
2015-12-11 10:36:10 -08:00
|
|
|
$char = uc $char if ($uppercase);
|
|
|
|
}
|
|
|
|
$result .= $char;
|
|
|
|
}
|
|
|
|
|
|
|
|
return "$result",
|
|
|
|
structured_answer => {
|
2016-01-04 08:00:12 -08:00
|
|
|
id => 'caesar_cipher',
|
|
|
|
name => 'Answer',
|
|
|
|
data => {
|
|
|
|
title => "$result",
|
2016-01-24 02:06:23 -08:00
|
|
|
subtitle => html_enc("Caesar cipher $shift_val $to_cipher"),
|
2016-01-04 08:00:12 -08:00
|
|
|
},
|
|
|
|
templates => {
|
|
|
|
group => 'text',
|
|
|
|
moreAt => 0,
|
|
|
|
},
|
2015-12-11 10:36:10 -08:00
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
1;
|