my %hash = ('apple2' => 'green', 'apple1' => 'green', 'banana' => 'yellow', 'plum' => 'red'); my %distinct; my %overflow; while (my ($k, $v) = each %hash) { # construct1 # (defined $distinct{$v}) ? ($overflow{$k} = $v) # : ($distinct{$v} = $k); # construct2 (exists $distinct{$v}) ? $overflow{$k} = $v : $distinct{$v} = $k; } for (keys %overflow) { print "$_, $overflow{$_} \n"; }