Sandwick
Sandwick

Reputation: 21

Check EOF while looping through file

I am reading file 15inv.txt line by line. I get the "item number" from each line and then open another file active.txt and search for a matching item number.

If I find a match, I want to print it out to results.txt with "matched" attached. If I get to the end of the file and do not find it print out "No match EOF reached".

I am trying to find whether the item number in 15inv.txt is in active.txt.

The 15inv.txt file looks like this. The file can have multiple item numbers.

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

The active.txt file has the item number in it and it only shows up once.

30-18
30-46
26817

Where am I going wrong in my code?

#!/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;

Upvotes: 0

Views: 754

Answers (1)

brian d foy
brian d foy

Reputation: 132820

I think you're asking about how to print something if you don't find it in the other file. Typically I use a flag variable for this. It's false until you find the thing. If it's still false when you've gone through the whole file, you didn't find it:

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

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

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

One way to detect these problems is to reduce your program to the smallest thing that can show the problem (rather than the entire working script). Try it in the small then build on that.

Upvotes: 2

Related Questions