in reply to Interesting Use of Grep

If the list of values that you are matching against is large then this method can get pretty inefficient. Remember that grep always checks every element of the array. In cases like that, it would be more efficient to do something like this:

my $found = 0; foreach (@long_list_of_values) { if ($var eq $_) { $found = 1; last; } } if ($found) { # do something... }
--
<http://www.dave.org.uk>

Perl Training in the UK <http://www.iterative-software.com>

Replies are listed 'Best First'.
Re: Re: Interesting Use of Grep
by japhy (Canon) on Jun 28, 2001 at 19:06 UTC

      not trying to re-obfuscate what we were trying to make simpler, but this would move everything back into one statement, instead of trying for $found and then testing it:

      for (LIST) { do{ something; last; } if ($_ eq $wanted) }

        just a point here,

        i've been burned by this one many times, please don't try to use a loop control statement (ie next, last, redo) inside of a do block. it'll fail1. And from personal experience, whenever you try to think of doing something that involves a loop control statement inside a do block, stop yourself from implementing said code. Your best bet would be to rethink what you're doing, and failing that ask the monks here for help. It is possible (and likely) that it is the best code for some situations, but more oft than not it won't be what you're looking for after you've written it.

        i'll also make the point, you could do a rewrite kinda like so:

        for(LIST) { do{ something } and last if ($_ eq $wanted) }
        which would work, but it's not very readable and there are definitely better solutions.

        Hope This Helps,
        jynx

        1 For further support of this look up p112 in Camel3.