自写的 Perl 模块的模块位置



我正在尝试在脚本中使用我的模块。

我知道您必须提供模块位置,并希望在脚本中提供路径。但是,我收到错误消息:

没有这样的文件或目录

这是我的脚本:

use strict;
use warnings;
use lib "C:/Users/XPS13/Documents/Uni/UEProgramming";
use Bioinformatics;
my $DNAinput = "restriction_test.txt";
open (my $FH_DNA_in, "<", $DNAinput) or die " Can't open file $DNAinput: $!n";
print "Pattern match for input file n";
print (Bioinformatics::Pattern($FH_DNA_in), "n"); #  applying module function  

这是我的模块

package Bioinformatics; # making module, 1st line contains name
use strict; # module uses strict and warnings 
use warnings;
sub Pattern {
my $count = "0";
my ($DNAinput) = @_;
open (my $FH_DNA_in, "<", $DNAinput) or die " Can't open file $DNAinput: $!n";
while (my $line = <$FH_DNA_in>) {
if ($line =~ /[AG]GATC[TC]/ ) { 
++ $count;
}
}
print "Your sequence contains the pattern [AG]GATC[TC] $count timesn";
}
1; # last line 

答:

模块位置有效。

发生错误是因为我打开了文件两次(在脚本和模块中)

当仅在模块中打开它时,它可以工作。更新后的脚本为:

use strict;
use warnings;
use lib "C:/Users/XPS13/Documents/Uni/UEProgramming";
use Bioinformatics;
my $DNAinput = "restriction_test.txt";
print "Pattern match for input file n";
print (Bioinformatics::Pattern($DNAinput), "n"); #  applying module function  

错误消息来自函数内部的open。在脚本中,打开一个名为$FH_DNA_in的文件句柄,然后将该文件句柄变量传递给函数

#        V
open (my $FH_DNA_in, "<", $DNAinput) or die " Can't open file $DNAinput: $!n";
#                              V
print (Bioinformatics::Pattern($FH_DNA_in), "n"); #  applying module function

在函数中,您可以将其用作要打开的文件的路径。

sub Pattern {
my $count = "0";
my ($DNAinput) = @_; # first arg was the filehandle!
#                           | this is the old filehandle
#        V different var    V
open (my $FH_DNA_in, "<", $DNAinput) or die " Can't open file $DNAinput: $!n";

该函数中的$FH_DNA_in是一个新的词法变量。它与旧的文件句柄无关,它最终以$DNAinput,因为这是您作为第一个(也是唯一的)参数传递的内容。

如果你在需要路径的地方使用文件句柄,Perl 会序列化它。它看起来像这样:

$ perl -E "open my $fh, '>', 'tmp'; say $fh;"
GLOB(0x26ba8c)

因此,它尝试查找具有该名称的文件,而该文件当然不存在。

您应该已经看到如下所示的完整错误消息:

无法打开文件 GLOB(0x26ba8c): 没有此类文件或目录

请注意,它不会告诉您错误发生在哪一行,因为您在要die的参数中包含换行符n。如果您没有这样做,那么加载模块会更明显,因为消息会更像

无法打开文件 GLOB(0x26ba8c):在 C:/Users/XPS13/Documents/Uni/UEProgramming/Bioinformatics.pm 第 9 行没有这样的文件或目录。

最新更新