Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: Array Comparison

by chromatic (Archbishop)
on Dec 22, 2003 at 18:32 UTC ( [id://316438]=note: print w/replies, xml ) Need Help??


in reply to Array Comparison

That nested loop is the killer. How about a hash? The following code is untested and unoptimized but performs better algorithmically:

my %exclude; @exclude{ @exclude } = (); my @cleaned = grep { exists $exclude{ $_ } ? () : $_ } @words;

Update: Yep, I confused grep with map in my pre-breakfast haste. That should rather be:

my @cleaned = grep { ! exists $exclude{ $_ } } @words;

Replies are listed 'Best First'.
Re: Re: Array Comparison
by Roy Johnson (Monsignor) on Dec 22, 2003 at 18:37 UTC
    I think that should be
    my @cleaned = grep { not exists $exclude{$_} } @words;
    Grep returns the original value for every element for which the expression returns true. Your ternary operator would be useful in map, but not here.

    The PerlMonk tr/// Advocate
      Excellent, this works much faster.

      Now, if I can just sort and make the list with just unique entries, I'm all set. Thanks.

        my @uniq = sort keys %{{map {$_ => 1} @cleaned}};
        or you could combine two statements in one (not recommended though :-) ...
        my @uniq = sort keys %{{map {$_ => 1} grep{not exists $exclude{$_}}@words}};

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://316438]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (6)
As of 2024-03-28 12:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found