Reputation: 95
my @words = qw(1 2 3 4 4);
my @unique_words = uniq @words;
print @unique_words; # 1 2 3 4
I am interested in finding which value was non-unique, in this case 4
. And being able to set it equal to a variable so that I can keep track of which specific value was re-occuring.
I want to do this so I can implement a code that says "if my string contains duplicating value from array completely remove duplicating value from array from string". In this case, if a string contained 1 2 3 4 4
. I would like it after the if statement to contain 1 2 3
.
Upvotes: 0
Views: 182
Reputation: 3925
Counting/finding duplicates is easiest done with a hash:
my %count;
$count{ $_ }++ for @words;
print "$_ occurs more than once\n"
for grep { $count{ $_ } > 1 } @words;
Finding the values that only occur once is done by looking for the elements in %count
that have a count of 1:
my %count;
$count{ $_ }++ for @words;
my @unique_words = grep { $count{ $_ } == 1 } @words;
Upvotes: 2