chenhao392的个人博客分享 http://blog.sciencenet.cn/u/chenhao392

博文

perl的代码阅读-1

已有 5321 次阅读 2011-3-22 04:10 |个人分类:学习|系统分类:科研笔记| 学习笔记

---阅读对象:某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例子:
  1. # same thing, but much more efficiently;
  2. # we'll build auxiliary indices instead
  3. # for speed
  4. my @nums = @caps = ();
  5. for (@old) {
  6. push @nums, ( /=(\d+)/ ? $1 : undef );
  7. push @caps, uc($_);
  8. }
  9. my @new = @old[ sort {
  10. $nums[$b] <=> $nums[$a]
  11. ||
  12. $caps[$a] cmp $caps[$b]
  13. } 0..$#old
  14. ];
 但是,为什么做了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:o: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){
...
}
难道只是少定义点变量,少用点内存么?





https://blog.sciencenet.cn/blog-395566-425000.html

上一篇:小鼠的生物信息实验操作总结--调侃效率
下一篇:blast2go本地安装,一个防火墙设置引发的血案
收藏 IP: 150.135.37.*| 热度|

1 杨华磊

发表评论 评论 (3 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-5-18 12:40

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部