+ -
当前位置:首页 → 问答吧 → Perl的一些代码阅读和探讨,欢迎指教

Perl的一些代码阅读和探讨,欢迎指教

时间:2011-03-22

来源:互联网

---阅读对象:某code
---字典:perl doc


片段1:
@sortedlist=reverse(sort { @tempa = split(/\t/,$a); @tempb = split(/\t/,$b); $tempa[9] cmp $tempb[9] || $tempa[0] <=> $tempb[0]; } @temp);


笔记:
$tempa[9] cmp $tempb[9] || $tempa[0] <=> $tempb[0];
先比较ID并排序(字符),如果一致,再比较match的大小(数字)。
参考perl-doc后,这个代码貌似有更高效率的写法,perl-doc例子:
# same thing, but much more efficiently;
# we'll build auxiliary indices instead
# for speed
my @nums = @caps = ();
for (@old) {
push @nums, ( /=(\d+)/ ? $1 : undef );
push @caps, uc($_);
}
my @new = @old[ sort {
$nums[$b] <=> $nums[$a]
||
$caps[$a] cmp $caps[$b]
} 0..$#old
];
但是,为什么做了index就更快呢?做index本身也要消耗时间啊,看来还得明白sort函数是怎么写的吧,也欢迎达人留言指教。     


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
片段2:
while(<ALL>{
        chomp;
        @temp = split(/\t/,$_);
        if($_=~/^\d+/){
                if(!defined $BestPSL{$_}){

                print OUT "$_\n";

                }
        }

}
用while和hash替代了一个可能的双for loop..
对比双for loop,代码优点在于:
1. while(<>是逐行读入,不占内存,没有等待读入内存的时间。
2. if(!defined $BestPSL{$_})巧妙的搜索了data,速度很快。


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
片段3:
use Getopt::Std;
use vars qw($opt_i $opt_o $opt_g $opt_c);
getopts('i:g:c:');

$Input=$opt_i;
$Output=$opt_o;
$AllowedGap = $opt_g;
$Color = $opt_c;

getopts 是ARGV的进阶版本,利器啊,这样写大型些的代码时,程序就没有那么凌乱了 。


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
片段4:
foreach (sort {$a cmp $b} keys %chr_len){
....
}

此处利用了perl的左向变量传递,但是,这和如下代码比,好在哪里呢?

my @key=keys(%chr_len);
my @sorted=sort{$a cmp $b} @key;

foreach(@sorted){
...
}
难道只是少定义点变量,少用点内存么?

作者: chenhao392   发布时间: 2011-03-22

第一个自己 Benchmark,没数据。不过原来的写法是挺慢的,每次比较都要 split。
第二个用 exists 测试存在性是不是更清晰点?
第四个没什么实际区别,注意好上下文分开写和写一起没什么区别

作者: zhlong8   发布时间: 2011-03-22