我正在尝试编译此代码,但它仍然为@fields和$ element变量获得相同的错误。据我所知,它不是一个范围错误,因为它是全局声明的。如果我不使用strict,它会被编译。
我提供了代码原型,请忽略任何输入错误。
#!usr/bin/perl
use strict;
use warnings;
use file::BaseName;
use file::Copy;
#my array declaration
my @fields;
#my other declarations
#input and output file initialization
while(<DATA1>) {
$String='';
$String= $_;
@fields= split(/,/,$String);
foreach my $elements(@fields){
#Some code
}
#more code
}
close (DATA1);
答案 0 :(得分:2)
您似乎已经跳过了大量可能隐藏问题的代码
您显示的内容
您尚未声明$String
,这应该是$string
file::BaseName
名为File::Basename
,file::Copy
拼写为File::Copy
#!usr/bin/perl
应为#!/usr/bin/perl
@fields
应该在首次使用时声明,而不是在文件的外层声明
但是,由于缺少这些,这些可能不是您错误的来源
尝试重写这部分代码
#!/usr/bin/perl
use strict;
use warnings;
use File::Basename;
use File::Copy;
# my array declaration
my @fields;
# my other declarations
# input and output file initialization
while ( <DATA1> ) {
my $string = $_;
@fields = split /,/, $string;
foreach my $elements ( @fields ) {
# Some code
}
# REST OF THE CODE
}
close DATA1;
答案 1 :(得分:0)
至少,您需要编译代码。 perl编译器通常非常有助于告诉您哪里出错了。这里有无效的包名,无效的perl路径,你应该使用DATA而不是DATA1。
尝试使用diagnostics
运行代码,因为它提供了更多信息:
perl -cwT -Mdiagnostics script.pl
Can't locate file/BaseName.pm in @INC (you may need to install the
file::BaseName module) (@INC contains: /etc/perl /usr/local/lib/i386-
... ) at foo2.pl line 4.
BEGIN failed--compilation aborted at foo2.pl line 4 (#1)
(F) You said to do (or require, or use) a file that couldn't be found.
Perl looks for the file in all the locations mentioned in @INC, unless
the file name included the full path to the file. Perhaps you need
to set the PERL5LIB or PERL5OPT environment variable to say where the
extra library is, or maybe the script needs to add the library name
to @INC. Or maybe you just misspelled the name of the file.
See "require" in perlfunc and lib.
Uncaught exception from user code:
Can't locate file/BaseName.pm in @INC (you may need to install the
file::BaseName module) (@INC contains: /etc/perl /usr/local/lib/i386-
... ) at foo2.pl line 4.
BEGIN failed--compilation aborted at foo2.pl line 4.
以下是您的代码的编译版本:
#!/usr/bin/perl
use strict;
use warnings;
use File::Basename;
use File::Copy;
my @fields;
while(<DATA>) {
my $String='';
$String= $_;
@fields= split(/,/,$String);
my $i = 0;
foreach my $element (@fields) {
print "[$i] : $element\n";
$i++;
}
}
__DATA__
foo,bar,baz
qux,1,2,3
<强>输出强>
[0] : foo
[1] : bar
[2] : baz
[0] : qux
[1] : 1
[2] : 2
[3] : 3