Skip to content

Instantly share code, notes, and snippets.

@trikitrok
Last active June 30, 2024 14:46
Show Gist options
  • Save trikitrok/127e7dc63925bb14fb95 to your computer and use it in GitHub Desktop.
Save trikitrok/127e7dc63925bb14fb95 to your computer and use it in GitHub Desktop.
#!/usr/bin/perl
use strict;
use warnings;
sub shiftChar {
(my $asciiVal, my $base, my $shift) = @_;
return chr(($asciiVal - $base + $shift) % 26 + $base );
}
sub isUpperCase {
my $asciiVal = shift;
return ($asciiVal >= 65 && $asciiVal <= 90);
}
sub isLowerCase {
my $asciiVal = shift;
return ($asciiVal >= 97 && $asciiVal <= 122);
}
sub charCipher {
(my $character, my $shift) = @_;
my $asciiVal = ord($character);
if (isLowerCase($asciiVal)) {
return shiftChar($asciiVal, 97, $shift);
}
if (isUpperCase($asciiVal)) {
return shiftChar($asciiVal, 65, $shift);
}
return $character;
}
sub charDecipher {
(my $character, my $shift) = @_;
return charCipher($character, - $shift);
}
sub transformText {
(my $text, my $shift, my $function) = @_;
return join('', map { $function->($_, $shift) } split('', $text));
}
sub caesarCipher {
return transformText(@_, \&charCipher);
}
sub caesarDecipher {
return transformText(@_, \&charDecipher);
}
my $text = "Todo lo que se preguntaba eran las mismas respuestas que buscamos el resto de nosotros. ¿De dónde vengo? ¿A dónde voy? ¿Cuánto tiempo tengo? Todo lo que pude hacer fue sentarme y ver como moría. z";
my $expectedSolution = "Wrgr or txh vh suhjxqwded hudq odv plvpdv uhvsxhvwdv txh exvfdprv ho uhvwr gh qrvrwurv. ¿Gh góqgh yhqjr? ¿D góqgh yrb? ¿Fxáqwr wlhpsr whqjr? Wrgr or txh sxgh kdfhu ixh vhqwduph b yhu frpr pruíd. c";
my $solution = caesarCipher($text, 3);
print "Caesar cipher is ok: ", $expectedSolution eq $solution, "\n";
print "Caesar decipher is ok: ", $text eq caesarDecipher($solution, 3), "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment