#!/usr/bin/perl use strict; use warnings; my $found_f = 0; my ($lastline, $line); open (INPUTFILE, "test.txt") or die "Unable to open test.txt: $!"; # 'or die' Added while () { chomp; if (/^[A-Z]{2}:\s/) { $lastline = $line; $line = $_; $found_f = 1; } elsif ($found_f) { s/^ {4}/ /; $line .= $_; } elsif (/^$/) { $lastline = ' '; $found_f =0; } } # Added $lastline .= $line; # Added - this was your main problem print "$lastline\n"; close (INPUTFILE); # Added