Last active
February 1, 2023 05:51
-
-
Save calid/6f89ecb8cae3d841c8b2 to your computer and use it in GitHub Desktop.
rot13 implementations, first on the shell and then in Perl
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
calid@xen ~ | |
[✔]▶ function rot13 { echo $1 | tr 'A-Za-z' 'N-ZA-Mn-za-m'; } | |
calid@xen ~ | |
[✔]▶ rot13 'Fraq hf gur pbqr lbh hfrq gb qrpbqr guvf zrffntr' | |
Send us the code you used to decode this message |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use strict; | |
use warnings; | |
my $UPPER_MIN = ord('A'); | |
my $UPPER_MAX = ord('Z'); | |
my $LOWER_MIN = ord('a'); | |
my $LOWER_MAX = ord('z'); | |
sub valid_uppercase { | |
my ($letter) = @_; | |
return ord($letter) >= $UPPER_MIN && ord($letter) <= $UPPER_MAX; | |
} | |
sub valid_lowercase { | |
my ($letter) = @_; | |
return ord($letter) >= $LOWER_MIN && ord($letter) <= $LOWER_MAX; | |
} | |
sub rot13_letter { | |
my ($letter) = @_; | |
my $r13; | |
if ( valid_uppercase($letter) ) { | |
$r13 = ord($letter) + 13; | |
if ($r13 > $UPPER_MAX) { | |
# wrap back to start of uppercase range | |
$r13 = $UPPER_MIN + $r13 % ($UPPER_MAX + 1); | |
} | |
} | |
if ( valid_lowercase($letter) ) { | |
$r13 = ord($letter) + 13; | |
if ($r13 > $LOWER_MAX) { | |
# wrap back to start of lowercase range | |
$r13 = $LOWER_MIN + $r13 % ($LOWER_MAX + 1); | |
} | |
} | |
if (!$r13) { | |
die "Invalid letter '$letter'"; | |
} | |
return chr($r13); | |
} | |
sub rot13_word { | |
my ($word) = @_; | |
return join '', map { rot13_letter($_) } split '', $word; | |
} | |
# make sure we really do have the list of words and not just quoted args, | |
# e.g. handle ./rot13.pl 'foo bar' 'baz quux' | |
my $args_string = join ' ', @ARGV; | |
my @words = split ' ', $args_string; | |
print join ' ', map { rot13_word($_) } @words; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Try this...
or as a one liner
perl -pe 'tr/A-Za-z/N-ZA-Mn-za-m/'
Of course these take a file or a pipeline, rather than converting an argument!