Hi all,
Howdy.
a while ago, I wrote a little subroutine to test wether a given element is in a given array:
sub contains {
my $result = 0; my $contained = shift; foreach (@_) { if ($_ eq $contained){ $result = 1; } } $result; }
That works, though I would probably drop the extra variable.
sub contains { my $contained = shift; foreach (@_) { return 1 if $_ eq $contained; } return 0; }
Now I found a nicer solution in "Learning Perl Objects, References & Modules" and adapted it:
sub contains { my $contained = shift; my $result = grep { $contained eq $_ } @_; }
Again, no need for the variable.
sub contains { my $contained = shift; return grep $_ eq $contained, @_; }
Smart. But immediately after giving this example, Randal notes that this is not the best solution for testing large arrays. Can anyone give me a hint to what he might have meant? Or, to put it this way: Randal, what did you think of writing this?
I'm not Randal, but will I do? <laughs>
The problem with both of your posted solutions is that they run the entire list of elements. The question is, "Is $contained in there somewhere?" That means that the first time we see it, we have answered that question. If we have 20,000 elements and we find it in the second slot, we waste 19,998 lookups, right?
We can't fix this in the grep() version, because grep() finds ALL matches, not just the first. It must walk the list to do its job. However, I snuck in a fix for your version above. Go take a peak...
James
-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>