• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 205
  • Last Modified:


What is the most efficient way to strip duplicates from an array?
1 Solution
perldoc perlfaq4

     a) If @in is sorted, and you want @out to be sorted:
             $prev = 'nonesuch';
             @out = grep($_ ne $prev && ($prev = $_), @in);
         This is nice in that it doesn't use much extra memory,
         simulating uniq(1)'s behavior of removing only adjacent
     b) If you don't know whether @in is sorted:
             undef %saw;
             @out = grep(!$saw{$_}++, @in);
     c) Like (b), but @in contains only small integers:
             @out = grep(!$saw[$_]++, @in);
     d) A way to do (b) without any loops or greps:
             undef %saw;
             @saw{@in} = ();
             @out = sort keys %saw;  # remove sort if undesired

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Train for your Pen Testing Engineer Certification

Enroll today in this bundle of courses to gain experience in the logistics of pen testing, Linux fundamentals, vulnerability assessments, detecting live systems, and more! This series, valued at $3,000, is free for Premium members, Team Accounts, and Qualified Experts.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now