use List::Util qw(max min); my %id_hash; open (DATA, ".txt"); while () { chomp; my ($order, $mtime, $size, $id, $date) = split /\t/; push @{ $id_hash{$order}{$id}{mtime} }, $mtime; push @{ $id_hash{$order}{$id}{size } }, $size; push @{ $id_hash{$order}{$id}{date } }, $date; } open (OUT, ">output.txt"); for my $order (keys %id_hash) { for my $id (keys %{ $id_hash{$order} }) { my $Low = min( @ { $id_hash{$order}{$id}{mtime} } ); print OUT "$order $Low \n"; } } #### open (OUT, ">output.txt"); open (IN, "input1.txt");->original file1 with all data while($line=){ chomp($line); ($Date,$MTime,$inserdate,$inserttime,$Id,$Phase,$Size,$day,$order)= split(/ /,$line); open (INL, "file2.txt");-->contains the sorted order values of order values($x) from file 1 while($linel=){ chomp($linel); ($x,$y,$z,$q,$t)= split(/ /,$linel); if($x == $order) { #print OUT "$a $x $b $z $q $t \n"; print OUT $Date," ",$M_Time," ",$inserdate," ",$y," ",$Id," ",$Phase," ",$Size," ",$day," ",$order,"\n"; } } } close(INL); close(IN); close(OUT); print "DONE";