Perl Weekly Challenge 045: Square Secret Code & Source Dumper
Square Secret Code
The square secret code mechanism first removes any space from the original message. Then it lays down the message in a row of 8 columns. The coded message is then obtained by reading down the columns going left to right.For example, the message is “The quick brown fox jumps over the lazy dog”. The code message would be as below:
tbjrd hruto eomhg qwpe unsl ifoa covz kxey
Let’s start with the test:
#!/usr/bin/perl
use warnings;
use strict;
use Test::More tests => 1;
is square_secret_code('The quick brown fox jumps over the lazy dog'),
'tbjrd hruto eomhg qwpe unsl ifoa covz kxey',
'encode';
Let’s use a regex to extract groups of 8 letters from the message. Then split each group into individual letters and append each of them to a string corresponding to an output word.
use Syntax::Construct qw{ /r // };
sub square_secret_code {
my ($message) = @_;
my @code = ("") x 8;
for my $group ($message =~ s/\s//gr =~ m/(.{1,8})/g) {
$code[$_] .= (split //, $group)[$_] // "" for 0 .. 7;
}
return join ' ', @code
}