遍历文件时检查 EOF

Check EOF while looping through file

我正在逐行读取文件 15inv.txt。我从每一行中获取 "item number",然后打开另一个文件 active.txt 并搜索匹配的项目编号。

如果找到匹配项,我想将其打印到 results.txt 并附上 "matched"。如果我到达文件末尾但没有找到它,则打印出 "No match EOF reached".

我正在尝试查找 15inv.txt 中的商品编号是否在 active.txt 中。

15inv.txt 文件如下所示。该文件可以有多个项目编号。

1 5,I413858,O313071 ,2015-5-11 12:01:01,10033,WHITE HOUSE FURNITURE                   ,FAIRFIELD           ,NJ,29562,1,460,460

active.txt 文件中有项目编号,它只出现一次。

30-18
30-46
26817

我的代码哪里出错了?

#!/usr/bin/perl -w

$inv = '15inv.txt';
open INV, "<$inv" or die "Unable to open the file\n";

$inv_out = '15inv-OBS.csv';
open INVOUT, ">$inv_out" or die "Unable to open the file\n";

$count = 0;
print INVOUT "Item #, Qty, Cost, Ext Cost, Status \n";

while ( <INV> ) {

    $inv_line = $_;
    chomp($inv_line);
    $count++;

    ($inv_rep, $inv_invoice, $inv_order, $inv_date, $inv_account, $inv_name, $inv_city, $inv_state, $inv_item, $inv_qty, $inv_cost, $inv_ecost)  = split(/,/, $inv_line);

    $inv_item =~ s/\s+//;  # remove spaces

    $active = 'active.txt'; # active items
    open ACTIVE, "<$active" or die "Unable to open the file\n";

    while ( <ACTIVE> ) {

        $the_active = $_;
        chomp($the_active);

        $active_item = substr($the_active, 0,10);

        $active_item =~ s/\s+//;
        next if ( $inv_item ne $active_item );

        if ( $inv_item eq $active_item ) {
            print INVOUT "$inv_item, $inv_qty, $inv_cost,$inv_ecost,IN \n";
            next;
        } # end of if 

    } # end of ACTIVE while loop

    print INVOUT "$inv_item, $inv_qty, $inv_cost,$inv_ecost, EOF \n";

} # end of INV while loop

print "Done!!! \n";

close FILE;
close INV;
close INVOUT;

exit;

我想你问的是如果你在其他文件中找不到它时如何打印它。通常我为此使用标志变量。在你找到那件事之前,它是假的。如果你遍历整个文件后还是false,说明你没找到:

my $look_for = ...;
my $found = 0;

while( <$fh> ) {
    chomp;
    $_ eq $look_for ? $found = 1 : next;
    ...
    }

unless( $found ) {
    print "Not found!";
    }

检测这些问题的一种方法是将您的程序减少到可以显示问题的最小部分(而不是整个工作脚本)。在小范围内尝试,然后在此基础上进行构建。