• + 0 comments

    Perl:

    sub caesarCipher {
        my @s = split("", shift);
        my $k = shift;
        my %shifted_alphabet;
        my $res;
        for (my $i = 97; $i <= 122; $i++) {
            if ((($k - 1) % 26)  + $i >= 122) {
                $shifted_alphabet{chr($i)} = chr((($k - 1) % 26)  + $i - 122 + 97);
            } else {
                $shifted_alphabet{chr($i)} = chr(($k % 26)  + $i);
            }
        }
    
        for (my $j = 65; $j <= 90; $j++) {
            if ((($k - 1) % 26)  + $j >= 90) {
                $shifted_alphabet{chr($j)} = chr((($k - 1) % 26)  + $j - 90 + 65);
            } else {
                $shifted_alphabet{chr($j)} = chr(($k % 26)  + $j);            
            }
        }
    
        for (my $h = 0; $h <= scalar(@s); $h++) {
            if (!exists($shifted_alphabet{$s[$h]})) {
                $res .= $s[$h];
            } else {
                $res .= $shifted_alphabet{$s[$h]};
            }
        }
    
        return $res;
    
    }