On 2013-01-20 04:43, Jim Gibson wrote:
On Jan 19, 2013, at 7:09 PM, Jun Meng <mengju...@gmail.com> wrote:
I need to extract items that happened once from an array. Here is an example
@my_array=qw (one, one, two, three, three, four);
The expected result: @new_array=("two", "four").
Could you give me some suggestion? The hash could remove duplicates, and
return ("one", "two", "three", "four"), which is not I want. I just want
the items that don't have any duplicates.
Use a hash to count the number of times each item appears in the array:
my %counts;
$counts{$_}++ for @my_array;
Then, extract the keys the have a count of 1:
my @new_array = grep { $counts{$_} == 1 } keys %counts;
And if you want to keep order:
my @new_array = grep { $counts{$_} == 1 } @my_array;
--
Ruud
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/