my @arr= nv.txt; my (%hash, $key, $val); foreach (@arr) { $pre1="\$hash{$key}"; #previous key of the loop $pre2=$val; #previous value of the loop ($key, $val) = split (/:/,$_,2); if($pre1 eq "\$hash{$key}") #if previous and current key same { $hash{$key}= $pre . '\n' . $val; #concatenate } $hash{key}=$val; print "\$hash{$key}={$vaal}\n"; }