Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

open two files for reading and searching 1

Status
Not open for further replies.

johno77

Technical User
Nov 1, 2003
40
0
0
GB
Hello

I havent used perl for a long time and am trying to refresh my memory to write a quick script - i have got the general jist of whatim doing but am still having a slight problems.

I am trying to open up a file of usernames for reading and then trying to find if the username is presnt within a SAM file (password file) - if it is then print the corresponding line in the password file. The script seems to work for the first found username but no others - if anyone has any ideas it would be appreciated

open (MYFILE, "test.txt"); //usernames file
open (MYFILE1, "test1.txt");

while ($record = <MYFILE>) {
chomp($record);

while ($record1 = <MYFILE1>) {
chomp($record1);
if ($record1=~m/$record/){print "$record1 \n";}

}

close(MYFILE1);

}

close(MYFILE);
 
Just a quick glance, but I think you'll need to move your second open statement to just after the first while.

open (MYFILE, "test.txt"); //usernames file

while ($record = <MYFILE>) {
open (MYFILE1, "test1.txt");
chomp($record);

while ($record1 = <MYFILE1>) {
chomp($record1);
if ($record1=~m/$record/){print "$record1 \n";}

}

close(MYFILE1); <- If you close here, the file never gets reopened

}

close(MYFILE);

Mark
 
Code indentation makes errors like this easy to spot, also use the [ code][ /code] tags, without spaces
Code:
open (MYFILE, "test.txt"); //usernames file
   while ($record = <MYFILE>) {
      chomp($record);
      open (MYFILE1, "test1.txt");
      while ($record1 = <MYFILE1>) {
         chomp($record1);
         if ($record1=~m/$record/){
            print "$record1 \n";
         }
      }
      close(MYFILE1);
   }
   close(MYFILE);

Depending on the size of the files there are much more efficient methods, such as reading the files into arrays, or hashes in memory rather than opening and closing files all the time
Code:
open (MYFILE, "test.txt");
@file1=<MYFILE>;
close MYFILE;
open (MYFILE2, "test2.txt");
@file2=<MYFILE2>;
close MYFILE2;
foreach $line (@file1) {
  foreach (@file2) {
    if ($_ =~ /$line/) { 
        print $line;
    }
  }
}
not as efficient as a hash would be, but it's going to be quicker than reading a file over and over

HTH

Paul
------------------------------------
Spend an hour a week on CPAN, helps cure all known programming ailments ;-)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top