[Charlotte.PM] find index of array element

William McKee william at knowmad.com
Wed Mar 23 03:27:08 PST 2005


On Tue, Mar 22, 2005 at 10:53:26AM -0500, Dale Lancaster wrote:
> Good challenge and one I need to do every now and then.  Too bad grep 
> doesn't return an index as an option.
> The best I could come up with on short notice:

Interesting approach. The form that I think Diona was recalling is in
the Cookbook as Recipe 4.13. To put it into your context, it would look
like the following:

  @matching = grep { /3/ } @input;

To get the first element, it would be:

  print $matching[0] - 1;

Though Drew's point about scalability is good to remember, I hardly
think you're going to have any issues with scalability until your arrays
get over 100 elements. Until then, grepping through an  array may be
faster than using a hash. Anyone care to write up that benchmark?


William

PS - Diona, thanks for the challenge!

-- 
Knowmad Services Inc.
http://www.knowmad.com


More information about the charlotte mailing list