if (open(FH, ") { my @columns = split(/\|/, $line); my $stage = 0; my $prefix; my @sections; my $sectionIndex = 0; foreach my $column (@columns) { next if ($column =~ m/^\s*$/); if ($column eq 'Q') { $stage++; next; } elsif ($column eq 'S') { $stage++; $sectionIndex++; next; } elsif ($stage == 0) { $prefix = ($prefix ? join('|', $prefix, $column) : $column); } else { $sections[$sectionIndex] = ($sections[$sectionIndex] ? join('|', $sections[$sectionIndex], $column) : $column); $sectionIndex++ if ($stage == 2); } } foreach my $section (@sections) { $section = join('|', $prefix, $section); } print join(' ', @sections)."\n"; } close(FH); }