Perl 如何循环通过ROT1-ROT25

Perl 如何循环通过ROT1-ROT25,perl,loops,Perl,Loops,到目前为止,我已经将其设置为对ROT25加密消息进行解码,并仅在其中包含单词“the”时才进行读取。但我必须让它经历每一次腐烂(1-25)。我知道这可能是一个循环,但不知道如何设置它 use English; my $file_name = shift; sub decode { return shift =~ tr/Z-ZA-Yz-za-y/A-Za-z/r; } open(my $file_handle, '<', $file_name) or die "Could no

到目前为止,我已经将其设置为对ROT25加密消息进行解码,并仅在其中包含单词“the”时才进行读取。但我必须让它经历每一次腐烂(1-25)。我知道这可能是一个循环,但不知道如何设置它

use English;

my $file_name = shift;

sub decode
{
    return shift =~ tr/Z-ZA-Yz-za-y/A-Za-z/r;
}

open(my $file_handle, '<', $file_name)
or die "Could not open file '$file_name' $!";

my $encoded = '';

{   # allow us to read entire file in as a string:

    local $INPUT_RECORD_SEPARATOR = undef;

    $encoded = <$file_handle>;
}

close $file_handle;

my $decoded = &decode($encoded);

if ($decoded=~m/(^| )the/)  # make this more robust!
{
    print($decoded);
}else{
print("File does not contain the, not the secret file");
}
使用英语;
我的$file\u name=shift;
子解码
{
返回移位=~tr/Z-ZA-Yz-ZA-y/A-ZA-Z/r;
}
打开(我的$file_句柄),尝试以下操作:

my $decoded = $encoded;
my $decodingFound;
for (1 .. 25) {
    $decoded = decode($decoded);
    if ($decoded =~ /\bthe\b/) {
        print($decoded);
        $decodingFound = 1;
        last;
    }
}

print("File does not contain the, not the secret file")
    unless $decodingFound;
注:

  • 这将尝试从ROT1到ROT2的所有ROT
  • 它从不检查原始(编码)字符串;为此,循环26次而不是25次
  • 一旦找到包含“the”的旋转,它就会停止查找
  • 正则表达式是
    \b
    \b
    表示单词二进制,因此
    “there”
    “father”
    都不匹配;从您的注释判断,这似乎是您想要的(“使它更健壮!”)
此外,您的旋转可能会缩短到
tr/ZA-Yza-y/A-ZA-z/r
z
z-z
)一样好,并且可能会比
tr/A-ZA-z/B-ZAb-ZA/r
更清晰。
my $decoded = $encoded;
my $decodingFound;
for (1 .. 25) {
    $decoded = decode($decoded);
    if ($decoded =~ /\bthe\b/) {
        print($decoded);
        $decodingFound = 1;
        last;
    }
}

print("File does not contain the, not the secret file")
    unless $decodingFound;