Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: The fastest way of searching a certain element in an array

by blakem (Monsignor)
on Apr 14, 2004 at 23:49 UTC ( [id://345252]=note: print w/replies, xml ) Need Help??


in reply to The fastest way of searching a certain element in an array

Try the first() function List::Util. Its like grep but returns as soon as it finds the first match.
% perldoc List::Util first BLOCK LIST Similar to "grep" in that it evaluates BLOCK setting $_ to +each element of LIST in turn. "first" returns the first element +where the result from BLOCK is a true value. If BLOCK never retur +ns true or LIST was empty then "undef" is returned. $foo = first { defined($_) } @list # first defined v +alue in @list $foo = first { $_ > $value } @list # first value in +@list which # is greater than + $value

-Blake

Replies are listed 'Best First'.
Re: Re: The fastest way of searching a certain element in an array
by ccn (Vicar) on Apr 15, 2004 at 22:56 UTC
    Hmm..., surely it is not the fastest. Here is it's code:
    sub first (&@) { my $code = shift; foreach (@_) { return $_ if &{$code}(); } undef; }
    You can see, it is similar to my for_block which was benchmarked.
      ccn,
      Here is it's code:

      Well that depends. As I indicated in Getting Matching Items From An Array, List::Util falls back to pure perl (which has obvious inefficiencies) only if the XS version is unavailable. Which version of 'first' did you use in your benchmarks?

      Cheers - L~R

        I benchmarked 'first' with XS loaded. To make shure that XS was loaded I've inserted some alerting printouts in pure perl version of the 'first'.

Re^2: The fastest way of searching a certain element in an array
by adamk (Chaplain) on Jan 17, 2005 at 03:52 UTC
    Or even better List::MoreUtil::any, which is EXACTLY what you mean. Boolean yes/no, instead of something that might suffer autoboolification and end up false.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://345252]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (2)
As of 2024-04-19 19:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found