原始代碼
代碼出處:http://www.perlmonks.org/index.pl?node_id=384100
#!/usr/bin/perl -w
use strict;
my$f= $[;my
$ch=0;sub l{length}
sub r{join"", reverse split
("",$_[$[])}sub ss{substr($_[0]
,$_[1],$_[2])}sub be{$_=$_[0];p
(ss($_,$f,1));$f+=l()/2;$f%=l
();$f++if$ch%2;$ch++}my$q=r
("\ntfgpfdfal,thg?bngbj".
"naxfcixz");$_=$q; $q=~
tr/f[a-z]/ [l-za-k]
/;my@ever=1..l
;my$mine=$q
;sub p{
print
@_;
}
be $mine for @ever
代碼重構(gòu)
B::Deparse 模塊是一個(gè)很好的打印機(jī),它可以揭開(kāi) Perl 代碼神秘的面紗,幫助你理解優(yōu)化器為你的代碼做了那些轉(zhuǎn)換。換言之,它會(huì)重新生成Perl代碼,試著略去一些晦澀難懂的部分,把代碼用一致的格式寫(xiě)出來(lái)。
使用 B::Deparse 模塊的一種方法:
復(fù)制代碼 代碼如下:
perl -MO=Deparse heart_raw.pl > heart_deparse.pl
輸出如下代碼:
復(fù)制代碼 代碼如下:
BEGIN { $^W = 1; }
use strict 'refs';
my $f = $[;
my $ch = 0;
sub l {
length $_;
}
sub r {
join '', reverse(split(//, $_[0], 0));
}
sub ss {
substr $_[0], $_[1], $_[2];
}
sub be {
$_ = $_[0];
p(ss($_, $f, 1));
$f += l() / 2;
$f %= l();
++$f if $ch % 2;
$ch++;
}
my $q = r("\ntfgpfdfal,thg?bngbjnaxfcixz");
$_ = $q;
$q =~ tr/[]a-z/[]l-p r-za-k/;
my(@ever) = 1 .. l;
my $mine = $q;
sub p {
print @_;
}
be $mine foreach (@ever);
代碼注釋
復(fù)制代碼 代碼如下:
#打開(kāi)警告開(kāi)關(guān)
BEGIN { $^W = 1; }
#符號(hào)引用檢查
use strict 'refs';
#數(shù)組中第一個(gè)元素的索引號(hào)
my $f = $[;
my $ch = 0;
#注意字符串中有個(gè)換行符
my $q = r("\ntfgpfdfal,thg?bngbjnaxfcixz");
$_ = $q;
$q =~ tr/[]a-z/[]l-p r-za-k/;
my (@ever) = 1 .. l;
my $mine = $q;
be($mine) foreach (@ever);
#獲取字符串的長(zhǎng)度
sub l {
length $_;
}
#反轉(zhuǎn)字符串
#join, 0均為湊數(shù)用,可以省略
sub r {
join '', reverse( split( //, $_[0], 0 ) );
}
#提取字符串中的子串
sub ss {
substr $_[0], $_[1], $_[2];
}
#輸出
sub p {
print @_;
}
#從字符串的前半段和后半段交替提取一個(gè)字符并輸出
sub be {
$_ = $_[0];
p( ss( $_, $f, 1 ) );
$f += l() / 2;
$f %= l();
++$f if $ch % 2;
$ch++;
}
代碼重寫(xiě)
復(fù)制代碼 代碼如下:
#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
my $pointer = 0;
my $character = 0;
my $string = reverse("\ntfgpfdfal,thg?bngbjnaxfcixz");
$string =~ tr/a-z/l-p r-za-k/;
foreach ( 1 .. length($string) ) {
print substr( $string, $pointer, 1 );
$pointer += length($string) / 2;
$pointer %= length($string);
++$pointer if $character % 2;
$character++;
}
代碼輸出
復(fù)制代碼 代碼如下:
kristen, will you marry me?