Now if you could benchmark "simplest" that would be a neat trick.

Well, one thing we might ask is which of two ways of doing something results in more work for the same result. In this case, pg's method produces less work because grep has to go through the entire list each time (and then, in scalar context, returns the number of times it found a match) whereas pg explicity returns when he finds the first occurrence. The are both linear, but grep will take about twice the time on average.

For this particular problem, a for loop is probably the Right Way To Do It&trade. Sure, grep can be used as could map, a C-style for, a while or until, or a couple well-placed goto statements with corresponding labels... but, that doesn't mean they should be. I do agree that, as the OP asked about it, the use of grep should be discussed and, ultimately, the reasons to avoid it should be explained. (An explanation goes a lot further than a benchmark.) But, I don't like showing him how to use grep with no explanation of why it isn't ideal because he's likely to be drawn to the simplicity of the idiom without considering its drawbacks.

-sauoq
"My two cents aren't worth a dime.";

In reply to Re^4: how to quickly tell if number is in an array by sauoq
in thread how to quickly tell if number is in an array by redss

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.