do_something() if (grep /something/, @array);
Actually, that doesn't bother me much at all. It is probably slower in most cases than some alternatives, but I'd probably only go about optimizing for that if I strongly suspected that @array was going to contain a whole lot of entries, many of which match /something/. But it is probably faster for cases where @array is quite large and most of the time none of its entries match /something/ (since the grep solution doesn't have to "dispatch" as many opcodes), so "premature optimization" could cost you here. Though I won't swear to anything without seeing benchmarks for a specific problem on a specific platform.
It would be neat if grep could tell that it is in a "Boolean context" and just give up as soon as it finds the first match. Unfortunately, I don't think Perl has context information other than 1) void, 2) scalar, 3) list, or 4) list assignment of size N, that is automatically tracked. I think such tracking is planned (perhaps waiting for Perl6 these days), so we may see such an automatic optimization in the future.
And I guess I should update my blanket statement on grep to be "So using grep to return something other than a subset of the original list (or, in a scalar context, the number of elements in that subset) is quite restricted and may be an indication that you shouldn't be using grep." With your code often being one of the exceptions in my book. (:
(but my friends call me "Tye")
Are you posting in the right place? Check out Where do I post X? to know for sure.
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
Want more info? How to link
or How to display code and escape characters
are good places to start.