我正在逐行阅读文件15inv.txt
。我从每一行得到“项目编号”,然后打开另一个文件active.txt
并搜索匹配的项目编号。
如果我找到一个匹配,我想打印到results.txt
并附上“匹配”。如果我到达文件的末尾并且没有找到它打印出“未达到EOF到达”。
我试图找出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;
我想如果你在另一个文件中找不到它,你会问如何打印。通常我会为此使用标志变量。在你发现这件事之前它是假的。如果在浏览完整个文件时它仍然是假的,那么你没有找到它:
my $look_for = ...;
my $found = 0;
while( <$fh> ) {
chomp;
$_ eq $look_for ? $found = 1 : next;
...
}
unless( $found ) {
print "Not found!";
}
检测这些问题的一种方法是将程序减少到可以显示问题的最小的东西(而不是整个工作脚本)。尝试在小,然后建立。