open my $file, "<" , "Filename" or die "$!"; my @buf; while (<$file>){ chomp; s/^\s*//; # Drop leading blanks s/\s*$//; # Drop trailing blanks if (0 == $. % 4){ # Processes the contents of @buf # it appears that something like this is what you need: print join(" ",@buf, $_), "\n"; @buf=(); # Reset it }else{ push @buf, $_; } } close $file; @buf and print @buf; # In case there is left-over stuff.