[Pdx-pm] read and concatenate two lines at a time

Michael G Schwern schwern at pobox.com
Sat Dec 4 00:22:47 CST 2004


On Fri, Dec 03, 2004 at 04:05:15PM -0800, Thomas J Keller wrote:
> Greetings, 
> I need to concatenate every two consecutive lines from a large data 
> file. Is there an easy way to do this? 

You're going to feel silly.

	while(my $entry = <>) {
	    $entry .= <>;
	    $entry =~ s/\n//g;	

	    ...do something with $entry...
	}


> Below is the snippet of what I tried, but it gives errors sometimes - 

The problem is described perfectly by your variable names and the fact
that they have nothing to do with what's actually in them.  See below.


> if anyone can point out why it works for some lines and not for others, 

Every forth line starts with a tab.  You're not taking that into account.


> while (<>){ 
> 	chomp; 
> 	my $line = $_; 
> 	$line =~ s/\t\./\t1/g;
>
> 	if ( $line =~ /^\w\w\d\d\d\d/) { 
> 		push @evens, $line; 
> 	} else { 
> 		push @odds, $line;  
> 	} 
> } 

You have two arrays.  @evens and @odds.  One would presume these contained
the even and odd lines of the file.  But there's no logic like that in
there at all!  Instead you're parsing the lines to determine which array
they go into. 

The way I showed above is simpler, but if you wanted to do it more like
your original code...

	while(my $line = <>) {
		chomp $line;

		# $. contains the line number of the last filehandle
		# accessed.
		if( $. % 2 == 0 ) {  # even line
			push @evens, $line;
		}
		else {
			push @odds, $line;
		}
	}

But this is more work than you need to do.


-- 
Michael G Schwern        schwern at pobox.com  http://www.pobox.com/~schwern/
I knew right away that my pants and your inner child could be best friends.


More information about the Pdx-pm-list mailing list