in reply to Re: Removing Duplicates from Array Passed by Reference
in thread Removing Duplicates from Array Passed by Reference
#! perl -slw use strict; sub dedup { my $ref = shift; my ($r, $l, %h); $r=$l=0; while( $r < @$ref ) { if ($h{$ref->[$r]}++) { # already seen ++$r; } else { # not yet seen. Copy! $ref->[$l++]= $ref->[$r++]; } }
This works by moving with two indizes (r-ight and l-eft) over the array, copying the right to the left if it hasn't be seen yet. At the end the length of the array is adjusted.$#$ref=$l-1 } my @a = (7, 20..30, 1..1000, 200..300, 7); print scalar @a; dedup \@a; print scalar @a; #print "@a";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Re: Removing Duplicates from Array Passed by Reference
by BrowserUk (Patriarch) on May 19, 2003 at 10:06 UTC | |
by Skeeve (Parson) on May 19, 2003 at 11:40 UTC |