Schedule
We meet TTh, 2:30 - 3:45 pm, in Bartlett 310
WEEK
7 Games
_____
Perl programs for Caesar Shifts:
Try running some Yardleygrams through these.
Encrypt
#! usr/bin/perl -w
# Let's declare our variables.
my $CT = "";
my $cShift = 0;
my $i = 0;
my $length_of_crypt = 0;
my @letter;
my $thisLetter = "";
my $thisLetterASCII = 0;
# First, we need to get the crypt. So, let's ask the user for it.
print "\nEnter crypt: ";
# Now, we need to take the user's input and place in tinside a variable.
# Let's call the variable CT for cipher-text. It must start with a dollar sign.
$CT = <STDIN>;
# We don't know what sort of nonsense the user might have typed. So we'll
# check it. Get rid of unwanted characters, punctuation, and spaces.
# We'll use the substitute function. s/x/y/ substitutes y for every x
# The character \W means everything that is not an alphanumeric
$CT =~ s/\W//gi;
# Now get rid of numbers
$CT =~ s/\d//gi;
# Now get rid of spaces
$CT =~ s/\s//g;
# Let's put the crypt into capital letters to make it consistent
$CT = uc($CT);
# Let's ask how much of a shift the user wants, not forgetting a new line
print "\nHow much of a Caesar Shift?: ";
$cShift = <STDIN>;
# Let's make sure it's a number and be curt about it
if ( $cShift =~ m/[0-9]+/)
{
if ($cShift > 25) {$cShift = 2; print "\nNot funny. Setting it to 2." }
}
else
{
print "\nNot a number. Goodbye.";
}
# Now, let's find out how many letters are in the crypt.
# That way, we can loop through the crypt and ceasar shift each letter
$length_of_crypt = length ($CT);
# Time to put each letter into a different variable. We'll use an array
@letter = split //, $CT;
# now, let's loop through every letter, change it to ASCII, add the shift
# and turn it back into a letter
for ($i=0; $i < $length_of_crypt; $i = $i +1)
{
$thisLetterASCII = ord($letter[$i]);
$thisLetterASCII = $thisLetterASCII + $cShift;
print chr($thisLetterASCII);
}
# clean up
print "\n";
_________________________
Decrypt
#! usr/bin/perl -w
# deshift a Caesar
my $CT = "";
my $cShift = 0;
my $i = 0;
my $length_of_crypt = 0;
my @letter;
my $thisLetterASCII = 0;
my $check = 0;
my $over = 0;
print "\nEnter crypt: ";
$CT = <STDIN>;
$CT =~ s/\W//gi;
$CT =~ s/\d//gi;
$CT =~ s/\s//g;
$CT = uc($CT);
$length_of_crypt = length ($CT);
@letter = split //, $CT;
for ($cShift = 0; $cShift < 26; $cShift = $cShift + 1)
{
for ($i=0; $i < $length_of_crypt; $i = $i + 1)
{
$thisLetterASCII = ord($letter[$i]);
$check = $thisLetterASCII + $cShift;
if ($check > 90)
{ $over = $check - 90;
$thisLetterASCII = 64 + $over;
}
else
{
$thisLetterASCII = $thisLetterASCII + $cShift;
}
print chr($thisLetterASCII);
}
print "\n";
}
|