📘 Caesar cipher using Perl 6

Encode a message using the Caesar cipher technique.

The Caesar code is a simple method of transcoding the letters of the message so that each letter is replaced with the letter that occurs in the alphabet N positions earlier or later.

For example, if N is 4, then the letter e becomes af is transformed to b, etc. The alphabet is looped so that z becomes v, and letters a to d become w to z.

The Str data type in Perl 6 is equipped with the trans method, which we have seen in Task 10, DNA-to-RNA transcription. It is also quite easy to use ranges in the replacement recipe:

my $message = 'hello, world!';

my $secret = $message.trans(
                 ['a' .. 'z'] => 
                 ['w' .. 'z', 'a' .. 'v']
             );
say $secret; dahhk, sknhz!

You can read the original message by translating it back with the same method but with swapped arrays:

say $secret.trans(
    ['w' .. 'z', 'a' .. 'v'] => 
    ['a' .. 'z']
);

Try modifying the solution so that it also works with the strings containing capital letters.

One thought on “📘 Caesar cipher using Perl 6”

  1. A note on the N offset : To offset the @letters array, one coud use the “rotate” method given an $offset, and negate $offset when decoding.
    Eg :
    $message.=trans( @letters => @letters.rotate( $offset ) );
    $message.=trans( @letters => @letters.rotate( – $offset ) );

    Liked by 1 person

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s