#!/usr/bin/env perl use utf8; ############################################################################### # This filter program encrypts/decrypts text using a Caesar Cipher. # Input text is taken from standard input and output text is written # to standard output. Assume only ASCII input/output. # # The first command line argument is the shift amount [0-25] # The second command line argument is the encrypt "e" or decrypt "d" # mode. # # Copyright © 2017 Richard Lesh. All rights reserved. ############################################################################### use Utils; use strict; use warnings; our $UPPER_ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; our $LOWER_ALPHA = "abcdefghijklmnopqrstuvwxyz"; our $ALPHABET_LEN = length($UPPER_ALPHA); MAIN: { if (scalar(@ARGV) != 2) { print Utils::messageFormat("Syntax: \{0:s\} 0-\{1:d\} e|d", "CaesarCipher1", $ALPHABET_LEN - 1), "\n"; exit 1; } my $SHIFT = Utils::stoiWithDefault($ARGV[0], 0); my $ENCRYPT = $ARGV[1] eq "e"; my $cp; while (defined($cp = Utils::getchar(*STDIN))) { my $alphabet; if (chr($cp) =~ m/^\p{Lower}/) { $alphabet = $LOWER_ALPHA; } else { $alphabet = $UPPER_ALPHA; } my $result = chr($cp); my $pos = index($alphabet, $result); if ($pos >= 0) { if ($ENCRYPT) { $pos = ($pos + $SHIFT) % $ALPHABET_LEN; } else { $pos = ($pos - $SHIFT + $ALPHABET_LEN) % $ALPHABET_LEN; } $result = substr($alphabet, $pos, 1); } print $result; } }