原始代碼
代碼出處: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
代碼重構
B::Deparse 模組是一個很好的印表機,它可以揭開 Perl 代碼神秘的面紗,協助你理解最佳化器為你的代碼做了那些轉換。換言之,它會重建Perl代碼,試著略去一些晦澀難懂的部分,把代碼用一致的格式寫出來。
使用 B::Deparse 模組的一種方法:
複製代碼 代碼如下:
perl -MO=Deparse heart_raw.pl > heart_deparse.pl
輸出如下代碼:
複製代碼 代碼如下:
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);
代碼注釋
複製代碼 代碼如下:
#開啟警告開關
BEGIN { $^W = 1; }
#符號引用檢查
use strict 'refs';
#數組中第一個元素的索引號
my $f = $[;
my $ch = 0;
#注意字串中有個分行符號
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);
#擷取字串的長度
sub l {
length $_;
}
#反轉字串
#join, 0均為湊數用,可以省略
sub r {
join '', reverse( split( //, $_[0], 0 ) );
}
#提取字串中的子串
sub ss {
substr $_[0], $_[1], $_[2];
}
#輸出
sub p {
print @_;
}
#從字串的前半段和後半段交替提取一個字元並輸出
sub be {
$_ = $_[0];
p( ss( $_, $f, 1 ) );
$f += l() / 2;
$f %= l();
++$f if $ch % 2;
$ch++;
}
代碼重寫
複製代碼 代碼如下:
#!/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++;
}
代碼輸出
複製代碼 代碼如下:
kristen, will you marry me?