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

Reading in multiple files simultaneously

Status
Not open for further replies.

ghung

Technical User
Oct 24, 2003
7
FI
Hi Folks,

I used to read in one file (unknown size)at a time and process each line one by one, like this:

open( IN1, &quot;<./infile1.txt&quot; );
foreach $line (<IN1>) {
if ($line =~ /.../) {
...
}
}

Now I need to read in two files (with same no. of lines) simultaneously and process one line from infile1.txt and the corresponding line from infile2.txt together before moving to the next line of both files.

Would any perl guru tell me how to do this? Many thanks in advance!!!

Regards,
Gary


Gary Hung
ASIC Design Engineer
 
Open file handles to both files. Then use a while statement to call both handles.

open IN1....
open IN2...

while (<IN1>) {
$file1line = $_
$file2line = <IN2>;
}

 
Additionally if the files are like list of names and second file is like their addresses you can read them both into 2 lists and just use the same index to pull the two records...

open(IN1,in1);
open(IN2,in2);

@IN1=<IN1>;
@IN2=<IN2>;

now you can do list things to match them up like $IN1[34] matches up to $IN2[34]


maybe something like

for($i=0;$i<=$#IN1;$i++) {
$line_from_1 = $IN1[$i];
$line_from_2 = $IN2[$i];
# do whatever...
}


this way if one file is longer/shorter you get all the data in and can test it with :

if (scalar @IN1 != scalar @IN2) ....

or whatever..

CGE
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top