If you pull out your handy dandy perldoc and type 'perldoc -q duplicate', which searches for the word 'duplicate' in the FAQ section of the perldoc, you come upon this handy entry:
ded430-deb-175-30:/home/buu/torrent# perldoc -q duplicat
Found in /usr/share/perl/5.8/pod/perlfaq4.pod
How can I remove duplicate elements from a list or array?
There are several possible ways, depending on whether the array
+ is ordered and whether you wish to preserve
the ordering.
a) If @in is sorted, and you want @out to be sorted: (this ass
+umes all true values in the array)
$prev = "not equal to $in[0]";
@out = grep($_ ne $prev && ($prev = $_, 1), @in);
This is nice in that it doesn't use much extra memory, simu
+lating uniq(1)'s behavior of removing only
adjacent duplicates. The ", 1" guarantees that the express
+ion is true (so that grep picks it up) even if
the $_ is 0, "", or undef.
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
e) Like (d), but @in contains only small positive integers:
undef @ary;
@ary[@in] = @in;
@out = grep {defined} @ary;
But perhaps you should have been using a hash all along, eh?
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|