#!/usr/bin/perl use strict; use warnings; my $input_file = 'HGDP.txt'; my $output_file = 'output.txt'; open my $fh, '<', $input_file or die "Unable to open for read $input_file: $!"; open my $out_fh, '>', $output_file or die "Unable to open for write $output_file: $!"; local $, = q{ }; local $\ = "\n"; my @rows; my $static_i = 3; # number of first unjoinable columns sub print_rows { print {$out_fh} @{$rows[0]}[0 .. $static_i - 1], map { my @columns; foreach my $x (0 .. $#rows) { push @columns, $rows[$x][$_]; } join q{/}, @columns; } $static_i .. $#{$rows[0]}; } while (defined(my $line_1 = <$fh>)) { my ($x) = $line_1 =~ /^(\d+)/ or next; push @rows, [split q{ }, $line_1]; while (defined(my $line_2 = <$fh>)) { next unless $line_2 =~ /^\d/; if ($line_2 =~ /^$x\b/) { push @rows, [split q{ }, $line_2]; } else { print_rows(); @rows = [split q{ }, $line_2]; last; } } } print_rows(); close $fh; close $out_fh;