in reply to Finding Redundant values in arrays

You can count occurrences using a hash:

@test = ("camel","alpaca","penguin","alpaca","monkey","camel","camel") +; my %counts; $counts{$_}++ foreach @test; @redundant = grep { $counts{$_}>1 } keys(%counts);

And please note that camels are never redundant <g>.

update: changed map to foreach so as to avoid the dreaded map in void context

Replies are listed 'Best First'.
Re: Re: Finding Redundant values in arrays
by ChemBoy (Priest) on Jun 08, 2001 at 01:11 UTC

    or, for slightly better performance (IIRC), ditch map in void context, and use

    $counts{$_}++ for @test;
    or (for us antediluvian 5.004 types)
    for (@test) {$counts{$_}++}

    I was hoping there was a Schwartzian Transform analog for this, just for the fun of running the whole thing into one line, but I can't come up with one.

    Update:
    No sooner posted than obsolete...

    @redundant = grep {++$counts{$_} > 1} @test;
    Oops!
    @redundant = grep {++$counts{$_}==2} @test;
    and a pox on foolish monks who post without full testing...



    If God had meant us to fly, he would *never* have give us the railroads.
        --Michael Flanders