foreach $file ( sort keys %csv_data ) { #file SCVG_ACE.txt foreach $item ( %{$csv_data{$file} }) { #item 13304_21114.01 if (exists($csv_data{$file}{$item})){ #if the item is found again add the filename to the #first element of the value $csv_data{$file}{$item} = s/^([^\|]*)\|/$1\/$file\|$csv_data{$file}{$item}/; } else { # maintain the normal data } } }