Contact US

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Little tricks

How do I count the unique elements of an array? by stillflame
Posted: 20 Jan 01

  Hashes automatically prevent you from having two
different keys with the same name.  If you assign different
values to the same element, the second one just rewrites
the first.  Thus, if you map an array onto the keys of a
hash with a value of one more than it's current value, you
get back a hash of elements corresponding to the unique
elements of an array and values equal to the number of
occurances of each.

sub count_unique {
    my @array = @_;
    my %count;
    map { $count{$_}++ } @array;

      #print them out:

    map {print "$_ = ${count{$_}}\n"} sort keys(%count);

      #or just return the hash:

    return %count;

 Alternatively, you could want to just get back an array of
the unique elements, not being concerned with the number of

sub return_unique {
    my @array = @_;
    my %count;
    map {$count{$_} = 1} @array;
    return sort keys(%count);

Back to Perl FAQ Index
Back to Perl Forum

My Archive

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close