0
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.

1
  • @toolic Thanks for the response! How do I print the value that was counted more than once with this implementation of code? Commented Oct 18, 2018 at 18:35

1 Answer 1

2

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;
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you that worked! Is there anyway that I can set $_, equal to a variable that holds the value that occurs more than once? So that I may be able to do comparisons globally in my program? Thank you very much for your guidance in advance.
What do you mean by "the value that occurs more than once"? There can be more than one value that occurs more than once. The expression grep { $count{ $_ } > 1 } keys %count; returns all the values that occur more than once. You can hold on that list by using my @duplicates = grep { $count{ $_ } > 1 } keys %count; .
or make the list of only non-duplicated values with my @non_duplicates = grep { $count{$_} == 1 } @words;
@ysth Thank you so much. That helped a lot. I think that was what I've been looking for.
@Corion Thank you, that helped a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.