Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi!

How do I print only those array elements that appears once (and not twice or more...) in an array?

Thanx...

update (broquaint): title change (was Arrays)

Replies are listed 'Best First'.
Re: finding unique elements in an array
by Aragorn (Curate) on Apr 02, 2003 at 08:23 UTC
    Use a hash to count the number of unique elements in the array:
    my %array_count; foreach my $elem (@array) { $array_count{$elem}++; } foreach my $key (keys %array_count) { print "$key\n" if $array_count{$key} == 1; }
    It probably can be done shorter, but I think this code conveys the idea quite clearly.

    The elements of the array become the keys of the hash, and the values of the hash are the number of times that the element is present in the array.

    Arjen

Re: finding unique elements in an array
by jmcnamara (Monsignor) on Apr 02, 2003 at 08:47 UTC

    Here is one way:
    #!/usr/bin/perl -wl use strict; my @many = (1,4,2,3,2,1); my %count; $count{$_}++ for @many; my @once = grep {$count{$_} == 1} @many; print "@many"; print "@once"; __END__ Prints: 1 2 3 2 1 4 3

    --
    John.

Re: finding unique elements in an array
by jonnyfolk (Vicar) on Apr 02, 2003 at 12:34 UTC
    I recently used this example from the Cookbook which worked very well for me...
    (There are other methods in the book so it's a highly recommended resource):
    %seen = (); @uniq = (); foreach $item (@list) { unless ($seen{$item}) { # if we get here, we have not seen it before $seen{$item} = 1; push(@uniq, $item); } }

    Update: Inserted missed bracket spotted by Martymart

      I tried two of these methods and they both worked for me... The method from zby was short and elegant looking, however the one from the cookbook gave me a result that more closely matched the input for some reason. Spotted a minor typo in that code though. Change line:unless ($seen{$item})to
      unless ($seen{$item}){

      Good answers to the question though,
      Martymart

Re: finding unique elements in an array
by zby (Vicar) on Apr 02, 2003 at 08:21 UTC
    Update: As aragorn pointed out that's wrong answer

    Here is my way to do it:

    @hash{@array} = @array; @onlyonce = keys %hash; print "@onlyonce";
      Although your solution uniqifies the elements of the array, it isn't possible to tell the number of times an element appears in the original array, which apparently is required.

      Arjen

        Hmm. I really can not find that requirement.
Re: finding unique elements in an array
by Anonymous Monk on Apr 02, 2003 at 08:42 UTC

    @h{@array}=undef; print for keys %h;