use strict; use warnings; use autodie; my %data=(); my $file_one = 'test.txt'; my $file_two = 'test2.txt'; open ( my $fh1, '<', $file_one); open ( my $fh2, '<', $file_two); my @data1 = <$fh1>; my @data2 = <$fh2>; for (@data1,@data2){ my ($sz,$sum,@f) = split /\s+/; push @{$data{$sz}},$_ for @f; } for my $sz (sort {$a <=> $b} keys %data){ print join ' ',@{$data{$sz}},"\n"; }