Home: Perl Programming Help: Regular Expressions:
Reading two lines at a time



blackeagle225
Novice

Jun 22, 2011, 12:11 PM


Views: 11009
Reading two lines at a time

Hello,

I have a data set, with 4 columns of data. I am trying to compare the element in the first row, column 4 with the second row, column 4 element. I am having a hard time, and would appreciate being pointed in the right directions. Thanks in advance.


miller
User

Jun 22, 2011, 1:48 PM


Views: 11008
Re: [blackeagle225] Reading two lines at a time

What have you tried thus far?

- Miller


blackeagle225
Novice

Jun 22, 2011, 1:59 PM


Views: 11007
Re: [miller] Reading two lines at a time

Hi Miller,

I tried a ton of different things, including seek, and loops within loops. I finally did figure it out. I just did

while (<FILE>) {
$CurrentLine = $NextLine;
$NextLine = $_;

....

It does require going through the loop one time to set both variables. Seems to be working now though. Thanks for your help anyway.


miller
User

Jun 22, 2011, 2:23 PM


Views: 11005
Re: [blackeagle225] Reading two lines at a time

Cool, glad you figured it out. I'd probably do something like the following:


Code
my $lastline = <FILE>; 

while (<FILE>) {
# Work with $_ and $lastline
...

$lastline = $_;
}



(This post was edited by miller on Jun 22, 2011, 3:09 PM)


FishMonger
Veteran / Moderator

Jun 23, 2011, 8:00 AM


Views: 10988
Re: [blackeagle225] Reading two lines at a time

I'd do it like this:

Code
while ( my $line1 = <$fh> ) { 
my $line2 = <$fh>;

}


My reasons: 1) it uses a lexical var for the filehandle, 2) it declares both vars in the smallest scope that the require, and 3) it doesn't needlessly use $_.


(This post was edited by FishMonger on Jun 23, 2011, 8:05 AM)


miller
User

Jun 23, 2011, 12:03 PM


Views: 10979
Re: [FishMonger] Reading two lines at a time

Agreed FishMonger,

However, does he want pairwise reading, or want to be doing logic on each adjacent line?

If based off his thread title, then yours would be the correct solution. But I think he actually wants to compare each line with it's adjacent, and your method would skip even pairs.

- Miller


rovf
Veteran

Jun 24, 2011, 5:12 AM


Views: 10967
Re: [blackeagle225] Reading two lines at a time

Since your implicitly require, that the input file contains an even number of lines, I would make this fact more explicit, even if the code looks a bit more complicated:


Code
while(1) { 
my $odd_line=<FILE>;
last unless defined $odd_line;
my $even_line=<FILE>;
die "This is odd: File has an odd number of lines\n" unless defined $even_line;
# process your pair of lines here
}



blackeagle225
Novice

Jun 24, 2011, 6:05 AM


Views: 10963
Re: [miller] Reading two lines at a time

Yeah, thanks Miller for understanding what I meant. Obviously still very green. I wanted to read a line, and read the next line and compare the two against one another. So far the program seems fine, but I appreciate all the help.