Skip to content

Instantly share code, notes, and snippets.

@ldante86
Last active May 14, 2018 07:47
Show Gist options
  • Save ldante86/81d87f6a84d743be20fd045bd0c06bbd to your computer and use it in GitHub Desktop.
Save ldante86/81d87f6a84d743be20fd045bd0c06bbd to your computer and use it in GitHub Desktop.
encode/decode Polybius cyphers
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
my $polybius;
my %polybius = (
"a" => "11",
"b" => "12",
"c" => "13",
"d" => "14",
"e" => "15",
"f" => "21",
"g" => "22",
"h" => "23",
"i" => "24",
"j" => "24",
"k" => "25",
"l" => "31",
"m" => "32",
"n" => "33",
"o" => "34",
"p" => "35",
"q" => "41",
"r" => "42",
"s" => "43",
"t" => "44",
"u" => "45",
"v" => "51",
"w" => "52",
"x" => "53",
"y" => "54",
"z" => "55",
);
sub help {
return << 'HELP';
polybius.pl - encode/decode Polybius cyphers
Usage: ./polybius.pl [-d] stdin
Option:
-d stdin decode cypher
Note: 'i' and 'j' encode to '24', but decoding '24'
will default to 'i'.
Quote multi-word strings on commandline.
HELP
}
sub encode {
my ($str) = (@_);
my $char;
for my $i ( 0 .. length($str) ) {
$char = substr( $str, $i, 1 );
if ( exists( $polybius{$char} ) ) {
print $polybius{$char};
}
}
print "\n";
}
sub decode {
my ($str) = (@_);
my $pair;
for ( my $i = 0 ; $i <= length($str) ; $i = $i + 2 ) {
$pair = substr( $str, $i, 2 );
foreach my $char ( keys(%polybius) ) {
if ( $polybius{$char} eq $pair ) {
if ( $pair eq '24' ) {
print "i"; # default to i
last;
}
else {
print $char;
}
}
}
}
print "\n";
}
die help if ( !@ARGV );
if ( $ARGV[0] eq '-d' ) {
shift;
die help if ( !@ARGV );
decode(@ARGV);
}
else {
encode("@ARGV");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment