0

"Use of uninitialized value $_ in print at finalhash.pl line 27, <$_[...]> line 7"编译此 Perl 代码时,我总是收到此错误。但是我的示例文件没有第 7 行。

如果第一列中的字符串与 file1.txt 第二列中的字符串匹配,我想打印出 file2.txt 的整行。

列用分号分隔。

这段代码改编自我之前发布的问题的另一个答案(感谢 Borodin)。有人能告诉我为什么在第一个 while 循环中第二列的值是 1:"$wanted{$fields[1]} = 1;"吗?

use strict;
use warnings;
use autodie;

my $fh;
my %wanted;

open $fh, '<', 'file1.txt';
chomp $fh;
while (my $line = <$fh>) {

    my @fields = split(';', $line);

    $wanted{$fields[1]} = 1;

}


open $fh, '<', 'file2.txt';
chomp $fh;
while (my $line = <$fh>) {

my @fields = split(';', $line);

   print if $wanted{$fields[0]};  #line 27 with the error


}

close $fh;
4

1 回答 1

1
open $fh, '<', 'file1.txt';
#chomp $fh;
while (my $line = <$fh>) {
    chomp $line;


open $fh, '<', 'file2.txt';
#chomp $fh;
while (my $line = <$fh>) {

通过这些更改,您的脚本应该可以正常运行。在读取的第一个文件中,您没有“咀嚼”$line。chomp $fh 毫无意义-什么都不做。

无需删除文件 2 中的换行符,因为您稍后将打印出来。

更新:马特在上面的评论中遇到了问题。打印 $line if ...

于 2014-04-22T15:51:31.403 回答