Beefy Boxes and Bandwidth Generously Provided by pair Networks Bob
Do you know where your variables are?
 
PerlMonks  

Yet Another Cryptogram Script

by missingthepoint (Friar)
on Mar 20, 2009 at 09:49 UTC ( #751968=sourcecode: print w/ replies, xml ) Need Help??

Category: Cryptography
Author/Contact Info missingthepoint
Description: Yes, another one.
use strict;
use warnings;
use List::Util qw(shuffle);

sub encode {
    my ($text, @alphabet) = @_;
    local $" = '';
    eval "\$text =~ tr/a-z/@alphabet/";
    $_ = uc for @alphabet;
    eval "\$text =~ tr/A-Z/@alphabet/";
    $text
}

sub decode {
    my ($text, @alphabet) = @_;
    local $" = '';
    eval "\$text =~ tr/@alphabet/a-z/";
    $_ = uc for @alphabet;
    eval "\$text =~ tr/@alphabet/A-Z/";
    $text
}

sub no_lt_ws {
    local $_ = shift;
    s/^\s+//;
    s/\s+$//;
    $_
}

my $opt = shift;
my $func;
my @alphabet;
if ($opt eq '-e') {
    $func = \&encode;
    @alphabet = shuffle('a'..'z');
}
elsif ($opt eq '-d') {
    $func = \&decode;
    local $| = 1;
    print "Alphabet: ";
    @alphabet = split /[^a-z]+/i, no_lt_ws(scalar <STDIN>);
}
else {
    die "Usage: $0 <-e(ncode)/-d(ecode)> [filenames]";
}

print "Alphabet: @alphabet\n";
while (<>) {
    print $func->($_, @alphabet);
}


Comment on Yet Another Cryptogram Script
Download Code
Re: Yet Another Cryptogram Script
by jwkrahn (Monsignor) on Mar 20, 2009 at 11:35 UTC
    sub encode { my ($text, @alphabet) = @_; local $" = ''; eval "\$text =~ tr/a-z/@alphabet/"; $_ = uc for @alphabet; eval "\$text =~ tr/A-Z/@alphabet/"; $text } sub decode { my ($text, @alphabet) = @_; local $" = ''; eval "\$text =~ tr/@alphabet/a-z/"; $_ = uc for @alphabet; eval "\$text =~ tr/@alphabet/A-Z/"; $text }

    Instead of running eval twice per subroutine you could do it like this:

    sub encode { my ($text, @alphabet) = @_; local $" = ''; eval "\$text =~ tr/a-zA-Z/\L@alphabet\U@alphabet\E/"; $text } sub decode { my ($text, @alphabet) = @_; local $" = ''; eval "\$text =~ tr/\L@alphabet\U@alphabet\E/a-zA-Z/"; $text }

      Good idea. :) And thanks - you made me realize my understanding of the \U-style escapes was a little fuzzy.


      "Half of all adults in the United States say they have registered as an organ donor, although only some have purchased a motorcycle to show that they're really serious about it."

Back to Code Catacombs

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: sourcecode [id://751968]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (8)
As of 2014-04-20 22:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (488 votes), past polls