randomG765
randomG765

Reputation: 63

PL/I - How do I read a file in a loop without opening/closing the file multiple times

I have a program that is reading through a file(FILE1). For every record in FILE1 it gets the field 'A' and it searches through FILE2 to find a record with a matching value of field 'B'. When A = B some fields from both files are read out. The program is currently working with code like below. However, the problem is I am opening and closing FILE2 in a loop, multiple times. I've tried this without opening the file inside the loop but if I do that I get repeated records as FILE2 is being read in from where the previous search left off. Is there any way I can point to the beginning of File2 every time I read a new record from FILE1? The code is below:

READ FILE(FILE1) INTO (IN_LAYOUT);
    DO WHILE (MORE_RECS1);
       OPEN FILE(FILE2);
       READ FILE(FILE2) INTO (IN_LAYOUT2);
       MORE_RECS2 = '1'B;
              DO WHILE (MORE_RECS2);
                 IF (A = B) THEN
                  DO;
                     VAL = VAL2;
                     WRITE FILE (OUFILE) FROM (OUT_LAYOUT);
                     S_MORE_RECS2 = '0'B;
                     CLOSE FILE(FILE2);
                  END; /* ENDIF */
                  ELSE READ FILE(FILE2) INTO (IN_LAYOUT2);
              END; /* INNER DOWHILE */
       READ FILE(FILE1) INTO (IN_LAYOUT);
    END; 

Upvotes: 0

Views: 1926

Answers (2)

Bruce Martin
Bruce Martin

Reputation: 10543

In this case @cschneid answer is the best solution. For for completeness there are other solutions available:

  1. Sort the 2 input files on the key and do the merge in your program
  2. Load File2 into a VSAM file and do a index lookup

Sort Merge processing

If you sort the 2 input files on the keys you can do:

DO WHILE (MORE_RECS1 and MORE_RECS2);
   if (key_file1 < key_file2) then do;
      READ FILE(FILE1) INTO (IN_LAYOUT);
   end; else if (key_file1 > key_file2) then do;
      READ FILE(FILE2) INTO (IN_LAYOUT2);
   end; else do;
      VAL = VAL2;
      WRITE FILE (OUFILE) FROM (OUT_LAYOUT);
      READ FILE(FILE1) INTO (IN_LAYOUT);
   end;
end;

Using this makes sense when the logic is to complicated for Sort (e.g. you need to DB lookups

Load File2 into a VSAM file

Another alternative is to load File2 into a VSAM file and do a keyed read. This can be useful to avoid doing expensive DB lookups multiple times (particularly with IMS which is less flexible than DB2).

In most cases the Sort-Merge processing above will be faster than VSAM lookup.

Upvotes: 1

cschneid
cschneid

Reputation: 10765

This looks like a match-merge. Try first sorting the files by the keys you're matching on.

At least some mainframe sort utilities have this match-merge functionality built in, Syncsort for example has the JOIN operator. I'm certain DFSORT also has this capability.

Upvotes: 2

Related Questions