1. 程式人生 > 實用技巧 >Perl呼叫和管理外部檔案中的變數(如軟體和資料庫配置檔案)

Perl呼叫和管理外部檔案中的變數(如軟體和資料庫配置檔案)

編寫流程時,有一個好的習慣是將流程需要呼叫的軟體、資料庫等資訊與指令碼進行分離,這樣可以統一管理流程的軟體和資料庫等資訊,當它們路徑改變或者升級的時候管理起來就很方便,而不需要去指令碼中一個個尋找再修改。

在shell程式設計中,我們可以通過source config.txt來獲取配置檔案config.txt中的變數。在Perl中,我們可以將這個功能編寫為一個模組,以後就都可以拿來直接用了。

假設配置檔案config.txt如下:

###########################
#######software path#######
###########################
codeml=/share/project002/bin/paml44/bin/codeml
formatdb=/opt/blc/genome/bin/formatdb
blastall=/opt/blc/genome/bin/blastall
muscle=/opt/blc/genome/bin/muscle

###########################
#######database path#######
###########################
go=/opt/blc/genome/go.fa
kegg=/opt/blc/genome/kegg.fa

針對配置檔案,我們可以寫一個名為Soft.pm的模組:

################################################
######This package contains the pathes of softwares and database
######You can modify the config.txt when the  path changed
################################################
package Soft;
use strict;
require Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw(parse_config);
##parse the software.config file, and check the existence of each software
################################################

sub parse_config{
        my ($config,$soft)=@_;
        open IN,$config || die;
        my %ha;
        while(<IN>){
                chomp;
                next if /^#|^$/;
                s/\s+//g;
                my @p=split/=/,$_;
                $ha{$p[0]}=$p[1];
        }
        close IN;
        if(exists $ha{$soft}){
                if(-e $ha{$soft}){
                        return $ha{$soft};
                }else{
                         die "\nConfig Error: $soft wrong path in $config\n";
                }
        }else{
                die "\nConfig Error: $soft not set in $config\n";
        }
}
1;              
__END__         

儲存後,在Perl指令碼中即可使用該模組:

#! /usr/bin/perl -w
use strict;
use FindBin qw($Bin $Script);
use lib $Bin;
use Soft; #呼叫模組
......
my $config="$Bin/config.txt";
my $blastall=parse_config($config,"blastall");
......

以上是使用相對路徑,如果是用絕對路徑,如下:

#! /usr/bin/perl -w
use strict;
use lib '/path/soft/';
use Soft;
......
my $config="/path/soft/config.txt";
my $blastall=parse_config($config,"blastall");
......

Ref:https://blog.csdn.net/hugolee123/article/details/38647011