in reply to Adding Unique Elements to Array

Does the order of the elements matter? If not, you could use hash keys instead.

my %h; for(qw/foo bar baz quux foo narf bar poit/) { $h{$_} = 1; }

If the order matters, you could keep a separate hash that has all of the items in it as keys.

my (%h, @a); for(qw/foo bar baz quux foo narf bar poit/) { push @a, $_ unless exists $h{$_}; $h{$_} = 1; }

Replies are listed 'Best First'.
Re^2: Adding Unique Elements to Array
by ww (Archbishop) on Feb 28, 2005 at 19:57 UTC
    Recall, however, that "last in wins" when populating a hash.

    OP appears to want not only to assure uniqueness (without testing) but also "only allow the value onto the array if it is not already included." (emphasis mine)

      But neither of the above solutions puts the elements in hash values. Either we're using the keys as an unsorted array directly, or using the keys as a separate boolean record of what's already in there.
Re^2: Adding Unique Elements to Array
by thekestrel (Friar) on Feb 28, 2005 at 18:46 UTC
    Thanks Friedo,
    The order does not matter actually, and as I was posting I was thinking about the use of a hash, just populating it with dummy data for key manipulation bothered me for some reason. Now that I think about it though that might be the best way to do it. Thanks =)
    Regards Paul
      That's the way I do it. It avoids having to test for duplicates (in my code, anyway). Also, if I need 'em in order I can use sort keys.. I'm relieved to see that mentioned here. I was afraid I was the only one doing it, and that there was a far better way.