生物信息学从零开始学生物信息学与算法

Perl学习15之生信分析中Perl简单运用(一)

2020-07-20  本文已影响0人  pythonic生物人

本文介绍:
perl如何读取excel表格?
perl如何读文件,存入哈希,输出到文件?
首发于本人公众号:pythonic生物人

更好的阅读体验请戳:

Perl学习15之perl读excel表格
Perl学习16之读文件,存入哈希,输出到文件

1、perl如何读取excel表格?

  • 常用于读取样本的背景信息、读取pooling表信息等。

表格的cell,row,col是什么?

image

#! /usr/bin/perl
use strict;
use warnings;
use Spreadsheet::XLSX;

#读入文件
my $excel = Spreadsheet::XLSX -> new ('./test.xlsx');
foreach my $sheet (@{$excel -> {Worksheet}}) {#Worksheet存储每个excel的sheet
        printf("SheetName: %s\n", $sheet->{Name});#输出sheet名字
       #判断sheet是否为空,等价于$sheet -> {MaxRow}=$sheet -> {MinRow}||$sheet -> {MinRow}
       $sheet -> {MaxRow} ||= $sheet -> {MinRow};
           #foreach my $row ($sheet -> {MinRow} .. $sheet -> {MaxRow}) {#行row循环,一行一行读
        foreach my $row ($sheet -> {MinRow} .. $sheet -> {MaxRow}) {#行row循环,一行一行读
               $sheet -> {MaxCol} ||= $sheet -> {MinCol};#判断每列是否为空
                                       my $cell1 = $sheet -> {Cells} [$row] [1];#第1列格子
                                       my $cell2 = $sheet -> {Cells} [$row] [2];
                                       my $cell8 = $sheet -> {Cells} [$row] [8];
                                           printf("%s\t%s\t%s\n", $cell1 -> {Val}, $cell2 -> {Val}, $cell8 -> {Val});
                                           #$cell -> {Val}为cell值
               }
       }

结果:

image 参考资料:

https://metacpan.org/pod/Spreadsheet::XLSX


2、perl如何读文件,存入哈希,输出到文件?

  • 常用于读取配置文件,譬如参考基因组hg19的路径、bwa的路径、下机数据的位置、输出结果的位置、日志文件的位置等。
#! /usr/bin/perl
use strict;
use warnings;

if(@ARGV!=2){
        print "\tUsage: perl $0 <infile>\n";
        die "\tUse with correct infile";
}
##读入文件$ARGV[0]存入哈希

#open IN, "<$ARGV[0]";
#open IN, "<","$ARGV[0]";
open IN,"$ARGV[0]" or die;#三种方式均可以打开句柄
my %para;#定义一个哈希

while(<IN>){
chomp;#chomp去掉末尾换行符
if(/^#/){next;};#跳过以#开头的行
if(/^$/){next;};#跳过空行
my ($k,$v)=split (/\=/,$_);#使用"="分割每行,每读取完一行后perl默认存储在$_里
$para{$k}=$v;#存入hash
}
close IN;#关闭句柄

my @key=keys %para;#keys函数取出哈希所有的键
my @value=values %para;#values函数取出哈希所有的值

##输出内容到$ARGV[1]
foreach my $key (@key){
        open OUT,">>","$ARGV[1]" or die;#打开输出文件句柄,">>"追加输出
        print OUT "$key\t$para{$key}\n";#输出值
        close OUT;#关闭句柄
}

perl open.pl test.para open1
输入文件test.para为:
###############paramenters##########
first_day=Monday
second_day=Tuesday
子敬=吴国

输出文件open1为:
子敬 吴国
first_day Monday
second_day Tuesday


干货,真香
上一篇 下一篇

猜你喜欢

热点阅读