LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Question about comparing one file to another in Perl (https://www.linuxquestions.org/questions/programming-9/question-about-comparing-one-file-to-another-in-perl-684961/)

HyperTrey 11-20-2008 02:06 PM

Question about comparing one file to another in Perl
 
I have a perl project that take a csv file and then process it. It will take the records and put them in different files depending on the results of the processing, such as, if the record is to many pages it will place the record in a bad record file and if the record is printed by an exempted staff member it will place the record in the staff file. There is a separate file that holds the exempted staff members

The problem I have is when I try to compare the record to the exempted staff file. Here is how I do it so far:

Code:

open(IN, "etc/except.txt");
(IN) || die "Unable to open exceptions!\n";
while(<IN>)  {
  chop;
  tr/A-Z/a-z/;
  push(@except, $_);
}
close(IN);

I then open the other files for the process and here is the section that does not work correctly:

Code:

while(<IN>)  {

$count = @except;
for ($i=0; $i<$count; $i++) {
            if ($a[5] = $except[$i]) {
                print STAFF "$_\n";
                next;
        }
    }

}


obviously there are other statements that process the rest of the records, but they work just fine. For some reason this ends up placing all record into the staff file. How do I get this fixed?

estabroo 11-20-2008 02:23 PM

instead of = try eq or == if its a numeric record, = is for assignment and evaluates true

HyperTrey 11-20-2008 02:39 PM

that worked, however is there anything I need to do other than that?

Like for ($i=0; $i<$count+1; $i++) { or something? It should not be cutting off the last name in the exempt file should it?

estabroo 11-20-2008 03:23 PM

$count = @except for the number of elements in the array should work just fine and your original loop should iterate through all the elements in except. You also probably want chomp instead of chop. You could make this more efficient by using a hash instead.


In your @except loading loop replace
push(@except, $_);

with
$except{$_} = 1;

and then eliminate that whole inner loop
Code:

$count = @except;
for ($i=0; $i<$count; $i++) {
            if ($a[5] = $except[$i]) {
                print STAFF "$_\n";
                next;
        }
    }

and replace it with
Code:

if ($except{$a[5]} == 1) {
        print STAFF "$_\n";
}


Sergei Steshenko 11-20-2008 05:26 PM

First and foremost, use

use strict;
use warnings;

in the beginning of you program/module - they show you a lot of problems.


All times are GMT -5. The time now is 05:26 PM.