在perl脚本中我收到错误:
无法在未定义的值
上调用方法getline
以下是代码的一部分。我使用Text::CSV
来读取文件:
my $csv = Text::CSV->new(
{ binary => 1,
encoding_in => "iso-8859-1",
encoding_out => "cp1252",
sep_char => ';'
}
);
open my $fhandle, '<:encoding(utf8)', $fileName
or die "Cannot use CSV:" . Text::CSV->error_diag();
while ( my $fields = $csv->getline($fhandle) ) {
push( @array, $fields->[0] );
push( @array, $fields->[1] );
push( @array, $fields->[2] );
}
答案 0 :(得分:2)
该错误消息具体表示变量$csv
未定义。
您是否正确实例化了?来自Text::CSV
的文档:
my $csv = Text::CSV->new ( { binary => 1 } ) # should set binary attribute.
or die "Cannot use CSV: ".Text::CSV->error_diag ();
检查代码中是否有这样的行(可能有不同的选项,这并不重要)。
请注意,您的错误die
- 与Text::CSV
无关,这是传统的文件打开。因此:
die "Cannot use CSV:".Text::CSV->error_diag ();
有误导性。如果您的open
失败,它仍然会出错,但它不会正确报告问题。你应该改为:
die "Error opening file: $!";
编辑:来自您正在使用的评论:
use Text::CSV;
my $csv = Text::CSV->new ({binary => 1, encoding_in => "iso-8859-1", encoding_out => "cp1252", sep_char => ';'});
尝试将其更改为:
my $csv = Text::CSV->new(
{ binary => 1,
encoding_in => "iso-8859-1",
encoding_out => "cp1252",
sep_char => ';'
}
) or die "Cannot use CSV: " . Text::CSV->error_diag();
您将收到以下错误:
Cannot use CSV: INI - Unknown attribute 'encoding_in' at line 2.
因此,您无法成功实例化$csv
对象,这就是您收到错误的原因。
您在Text::CSV
中引用的代码如下所示:
use Text::CSV::Encoded;
my $csv = Text::CSV::Encoded->new ({
encoding_in => "iso-8859-1", # the encoding comes into Perl
encoding_out => "cp1252", # the encoding comes out of Perl
});
E.g。使用不同的模块 - Text::CSV::Encoded
答案 1 :(得分:2)
错误的open()导致了getline错误
修改:
open my $fh, "<:encoding(utf8)", "test.csv" or die "test.csv: $!";
while ( my $row = $csv->getline( $fh ) ) {
}
将$ file替换为&#34; test.csv&#34;创造了这个问题。
my $csv = Text::CSV->new ({binary=>1}) ;
$file = "test.csv" ;
if(!open($fh, "<", $file )) {
# Cannot call getline is a symptom of a bad open()
printf("### Error %s: could not open file %s\n", $ws, $file) ;
close($fh) ;
exit 1 ;
}
while(my $row = $csv->getline($fh)) {
@items = @{$row} ;
for(my $i=0 ; $i<=$#items; $i++) {
printf("Field %d: (%s)\n", $i, $items[$i] ) ;
}
}