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 Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help Trying to read from 2 files at same time 2

Status
Not open for further replies.

chorgan

Programmer
Jun 19, 2001
5
IE
Im trying to produce results like

Line from fileA
Line from fileB
Line from fileA
Line from fileB etc

I have code like this
while(<fileA>)
{
print line
open fileB
while(<fileB>)
{
some processing
print line from fileB
}
close(fileB);
}
close(fileA);
Im using $_ to access a line but its only picking up the line from the 1st file not from the second so i get each line printed twice. WHY? dear GOD why??????
 
I would suggest that you are doing this in a fairly inefficient way. You are opening and closing fileB for every line in fileA. Instead, you might throw the contents of each into two arrays and then just alternate lines from the two arrays. I just typed this and have not run it. It may need a tweak or two, but, hopefully you see the general flow.

Code:
#!/usr/local/bin/perl
open(INPUT1,&quot;<fileA&quot;) or die &quot;Failed to open fileA, $!\n&quot;;
while (<INPUT1>)     {     push @a_Lines, $_;     }
close INPUT1;

open(INPUT2,&quot;<fileB&quot;) or die &quot;Failed to open fileB, $!\n&quot;;
while (<INPUT2>)    {     push @b_Lines, $_;     }
close INPUT2;

open(OPF, &quot;>new_file_name&quot;) or die &quot;Failed to open new output file, $!\n&quot;;
for ($i=0,$i<$#a_Lines, $i++)
    {
    print OPF &quot;$a_Lines[$i] $b_Lines[$i]&quot;;
    }
close OPF;

HTH


keep the rudder amid ship and beware the odd typo
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top