#!/usr/bin/perl use strict; use warnings; # NOTE: The @sourcedata array is the representation of # the data as if it were read from a file by: # # open(FH, $sourcefilename) || die ... # my @sourcedata = ; # close FH; # # Since the source file is huge, I need to process the # file line by line # NOTE: I updated this array to reflect an array of lines my @sourcedata = ( "\n", "1\n", "\n", "\n", "b\n", "\n", "1\n", "\n", "\n", "\n", "\n", "_____ 2\n", "\n", "\n", "\n" ); # The desired result of processing a small data sample: my @desiredoutput = qq( 1 b 1 _____ 2 # NOTE: preceding newlines have been collapsed ); #### my @buffer = (); my $length = scalar @sourcedata; for (my $I = 0; $I < $length; $I++) { my $line = $sourcedata[$I]; if ($line =~ /^1$/) { push(@buffer, $line); $I++; $line = $sourcedata[$I]; # Here's the loop I can't seem to execute: while ($line =~ /^\n$/ && $I != $length) { print "Buffering...\n"; push(@buffer, $line); $I++; last if $I == $length; $line = $sourcedata[$I]; } if ($line =~ /_____ 2/) { # print only the first and last items in the buffer, # effectively removing the empty lines print shift(@buffer), pop(@buffer); print $line; } else { print join(@buffer); } } else { print $line; } @buffer = (); }