in reply to Comparing Two Arrays

my @array1 = (1, 2, 3); my @array2 = (3, 4, 5); my %union = (); map { $union{$_}++ } (@array1, @array2); my @array3 = keys %union;
Update: dragonchild is right. map is slower than a for loop. Use his code above, but you should still learn the wonderful world of map!

Update2:I like this one by danboo the best: @array3 = keys %{{ map {$_ =>1} @array1, @array2 }}; It uses map in a non-void context, does a simple assignment operation instead of the addition/auto-vivify, and is still quite readable. Am I wrong? Is there a more optimized solution?

Replies are listed 'Best First'.
Re: Re: Arrays
by dragonchild (Archbishop) on Dec 08, 2001 at 00:47 UTC
    Just to nitpick - using map in a void context is generally considered poor style. It's also slower than the corresponding for loop. (And, almost always, less characters, closer to English, and uses "less complex" syntax.) *shrugs*

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

      Yeah, well, map pays me a monthly fee to use it everywhere possible. It's a whole marketing campaign. Soon you'll see got map? stickers on ThinkGeek.com and banner ads on PerlMonks and Slashdot - "First map!".

      Sorry.. :) I'm just a map fan.
        Yeah, well, map pays me a monthly fee to use it everywhere possible.

        Its just not fair. map gets all the attention even when half his work goes to waste. Just keep in mind that and really could use the work :-)

Re: Re: Arrays
by rje (Deacon) on Dec 08, 2001 at 00:47 UTC
    Ah, you used map(). I'm going to have to learn that
    function and start using it.

    Rob