develooper Front page | perl.beginners | Postings from February 2002

Re: unique elements in array

Thread Previous
From:
Jeff 'japhy' Pinyan
Date:
February 26, 2002 08:05
Subject:
Re: unique elements in array
Message ID:
Pine.GSO.4.21.0202261104220.19152-100000@crusoe.crusoe.net
On Feb 26, Simon K. Chan said:

>The solution to my question is probably dead easy, but the bioperl
>module I'm working on right now has sucked up all by brain juice! ;-)
>
>Let's say I have this array:
>
>@food = qw(milk ham eggs bread eggs milk);
>
>How can I write a script that sticks all UNIQUE elements (occurs only once) into another array?
>So, in the above case, @another_array would receive "ham" and "bread"

You'll want to use a hash:

  $count{$_}++ for @food;
  @unique = grep $count{$_} == 1, keys %count;

Hashes are the answer to many questions.

-- 
Jeff "japhy" Pinyan      japhy@pobox.com      http://www.pobox.com/~japhy/
RPI Acacia brother #734   http://www.perlmonks.org/   http://www.cpan.org/
** Look for "Regular Expressions in Perl" published by Manning, in 2002 **
<stu> what does y/// stand for?  <tenderpuss> why, yansliterate of course.
[  I'm looking for programming work.  If you like my work, let me know.  ]


Thread Previous


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About