in reply to extracting redundant and unique items

I'm sure there has to be a better way to do it than the way I have here, but one way would be to iterate over that array and putting each spot into a hash as the key. Then once that is done, you can get the array of the keys of that hash and you have your unique values.

Like I said, that is ugly and probably wasteful - but it is the first thing that popped into my head.

Here is some totally untested code:
my @array = ('11','54','23','78','54','54','78'); my %hash; foreach $thing (@array){ #increment it in case for some reason you later want a # count of how many each are in the orig array $hash{$thing}++; } my @unique = keys %hash;


-------------------------------------------------------------------
There are some odd things afoot now, in the Villa Straylight.

Replies are listed 'Best First'.
Re: Re: extracting redundant and unique items
by Limbic~Region (Chancellor) on May 14, 2003 at 19:36 UTC
    AssFace,
    I have been told that if you are going to throw away the values it is better not to even bother assigning the hash keys:
    $hash{$thing}++; versus $hash{$thing} = undef;
    I am not one for cargo cult programming. I honestly want to know why something is a better idiom for something than just doing it. With this said, I haven't thoroughly investigated this. I did do some benchmarks and the undef came out faster. Additionally, it makes sense that it isn't allocating any memory or doing any computation of the value.

    Cheers - L~R

      That does make sense - since it doesn't do anything in terms of allocating memory for it and the like.

      I was mainly thinking in case they later wanted to know that there were 15 instances of X, 12 instances of Y, and 2 instances of Z, then the code would have that...

      But since they didn't say anything about wanting that, I suppose it would make more sense to do the undef instead and then later easily add in addition functionality like counting.

      -------------------------------------------------------------------
      There are some odd things afoot now, in the Villa Straylight.