my %id_hash; my @lines = (); open (DATA, "test.txt"); while ($line = ) { chomp $line; my @line = split /\t/ , $line; push @lines, \@line; # push the original line in an array as an anonymous array if ($line[1] > $id_hash{$line[0]}) {$id_hash{$line[0]} = $line[1];} # calculate the biggest mtime for a given order id } open (OUT, ">output.txt"); foreach my $item (@lines) { my @line = @{$item}; # get the original line $line[4] = $id_hash{$line[0]}; # replace the fifth element with the calculated maximum print OUT join "\t" ,@line, "\n"; # print the adapted line }