代码出处: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 模块的一种方法:
输出如下代码:
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++;
}
代码输出