use strict; use warnings; my $file = "z.txt"; open my $fh, "<", $file or die "Unable to open $file: $!"; my ($p_val, $m_val); { local $/ = '\n\n\n'; while (<$fh>) { foreach (split/\n/) { if (s/\bProcessing\s\d+\.tx\.\d+: //) { print "$_\n"; } elsif (s/\bPhrase: //) { s/"//g; $p_val = $_; } elsif (/^\s\s(.+)/) { $m_val = $_; if (defined $p_val) { print "\t$p_val\t$m_val\n"; undef $p_val; ### moved undef here } else { ### new else condition print "\t\t$m_val\n"; } } } } } close $fh; __END__ Pulmonary embolism at the time of hip replacement Pulmonary embolism 1000 D0076131:PULMONARY EMBOLISM Disease or Syndrome of hip replacement 1000 D0554893:HIP REPLACEMENT (STATUS POST HIP REPLACEMENT) Finding of hemorrhage 1000 D0046004:HAEMORRHAGE (BLEEDING) Finding 1000 D0046011:HAEMORRHAGE NOT OTHERWISE SPECIFIED (HEMORRHAGE NOT OTHERWISE SPECIFIED) Finding