[lug] perl question
rm at fabula.de
rm at fabula.de
Tue Jun 4 04:43:15 MDT 2002
On Tue, Jun 04, 2002 at 10:15:27AM +0000, j davis wrote:
>
>
> hi,
>
> this little piece of perl removes dups from a list..
> so they tell me. does anyone here speak extreme laymen
> ?
>
is this a question/riddle?
Ok, the first question would be: do you need to preserve the
order of the list?
# given the following list
my @list = ('a', 'b', 'c', 'd', 'b', 'f', 'e', 'e');
-No, i don't. Then:
# read the list into an hash
# If an item is seen more than once, the hash value
# for it will be > 1, but we don't care ...
my %seen = undef;
map { $seen{$_}++ } @list;
# ... since we get the list via
@unique_list = keys %seen;
-Yes, i want it ordered. Then:
my @unique_list = grep {
if(!$seen{$_})
{
$seen{$_}++;
$_;
}
} @list;
Ok, this _is_ a bit cryptic, but it works.
Basically, you use the hash as a marker storage, for each item
in the list, look up whetherwe have 'seen' it allready, if not,
return it (i.e. pass it on to @unique_list) and mark it, else just
pass on to the next list entry.
Hope that helps
Ralf
>
>
>
> _________________________________________________________________
> Chat with friends online, try MSN Messenger: http://messenger.msn.com
>
> _______________________________________________
> Web Page: http://lug.boulder.co.us
> Mailing List: http://lists.lug.boulder.co.us/mailman/listinfo/lug
> Join us on IRC: lug.boulder.co.us port=6667 channel=#colug
More information about the LUG
mailing list