From 05e96cba9ec7a4b3369202dd79b7873fba04f416 Mon Sep 17 00:00:00 2001 From: Steven Wilson Date: Tue, 2 Jul 2019 20:06:49 +0100 Subject: improve encode/decode subroutines --- challenge-015/steven-wilson/perl5/ch-2.pl | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/challenge-015/steven-wilson/perl5/ch-2.pl b/challenge-015/steven-wilson/perl5/ch-2.pl index e9c262d986..543be7ee3b 100644 --- a/challenge-015/steven-wilson/perl5/ch-2.pl +++ b/challenge-015/steven-wilson/perl5/ch-2.pl @@ -16,8 +16,7 @@ use warnings; use feature qw / say /; use Test::More; -my @alphabet = ("A".."Z"); -my ($operation, $keyword, $in_text) = ($ARGV[0], $ARGV[1], $ARGV[2]); +my ( $operation, $keyword, $in_text ) = ( $ARGV[0], $ARGV[1], $ARGV[2] ); my $out_text; my %operations = ( '-e' => 'encrypted', @@ -28,11 +27,11 @@ ok( encode( "ATTACKATDAWN", "LEMON" ) eq "LXFOPVEFRNHR", "encode working" ); ok( decode( "LXFOPVEFRNHR", "LEMON" ) eq "ATTACKATDAWN", "decode working" ); done_testing(); -if ($operation eq "-e"){ - $out_text = encode($in_text, $keyword); +if ( $operation eq "-e" ) { + $out_text = encode( $in_text, $keyword ); } -elsif ($operation eq "-d"){ - $out_text = decode($in_text, $keyword); +elsif ( $operation eq "-d" ) { + $out_text = decode( $in_text, $keyword ); } else { die "$operation is not a valid operation"; @@ -43,10 +42,10 @@ say "Message $operations{$operation} to '$out_text'"; sub encode { my ( $plaintext, $keyword ) = @_; my $cyphertext; - for my $i (0..((length $plaintext) - 1)){ - (my $mi) = grep { $alphabet[$_] eq substr($plaintext, $i, 1) } (0..@alphabet-1); - (my $ki) = grep { $alphabet[$_] eq substr($keyword, ($i % length $keyword), 1)} (0..@alphabet-1); - $cyphertext .= $alphabet[($mi + $ki) % 26]; + for my $i ( 0 .. ( ( length $plaintext ) - 1 ) ) { + my $mi = ord( substr( $plaintext, $i, 1 ) ) - 65; + my $ki = ord( substr( $keyword, ( $i % length $keyword ), 1 ) ) - 65; + $cyphertext .= chr( ( ( $mi + $ki ) % 26 ) + 65 ); } return $cyphertext; } @@ -54,10 +53,10 @@ sub encode { sub decode { my ( $cyphertext, $keyword ) = @_; my $plaintext; - for my $i (0..((length $cyphertext) - 1)){ - (my $ci) = grep { $alphabet[$_] eq substr($cyphertext, $i, 1) } (0..@alphabet-1); - (my $ki) = grep { $alphabet[$_] eq substr($keyword, ($i % length $keyword), 1)} (0..@alphabet-1); - $plaintext .= $alphabet[($ci - $ki) % 26]; + for my $i ( 0 .. ( ( length $cyphertext ) - 1 ) ) { + my $ci = ord( substr( $cyphertext, $i, 1 ) ) - 65; + my $ki = ord( substr( $keyword, ( $i % length $keyword ), 1 ) ) - 65; + $plaintext .= chr( ( ( $ci - $ki ) % 26 ) + 65 ); } return $plaintext; } -- cgit