my $line_number = 0; foreach my $row(@content){ # count the current line number $line_number++; # remove the newline chomp($row); my $rowsaver = $row; if($rowsaver=~/^\d/){ # curent row starts with a decimal # no extra action required, just process it }else{ # ok, current row does not start with a decimal, # we need to add a newline to the output file # before we process this line print $fh "\n" if $line_number > 1; } : rest of your code #### my $have_to_newline = $rowsaver=~/^\d/ ? 1 : 0 print $fh "\n" if $have_to_newline && $line_number > 1;