Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Search array without a loop?

Status
Not open for further replies.

LucL

Programmer
Jan 23, 2006
117
US
Is it possible to search a simple perl array (@arr) without a loop to find an exact match?

Thanks!
Luc L.
 
Do you mean "is there some syntactic sugar because I'm too lazy to write a loop" or "I have to compare 5,000,000 records against a list of 5000 possible exact matches, and I'm worried about performance"?

If it's the former, just bite the bullet and write the loop. If it's the second option, you could try something like
Code:
use strict;
use warnings;

my %match;

while (<DATA>) {
	chomp;
	$match{$_}++
}

while (<>) {
	my ($lookup, $junk) = split(/:/, $_, 2);
	print "Matched \'$lookup\' at line $.\n" if exists $match{$lookup};
}

__DATA__
some
stuff
to
match
against
run against a file testdata.txt of
Code:
a:
b:
c:
d:
against:
e:
f:
g:
5000000:records later
to:
would be way faster, as once you have the hash loaded the match/nomatch decision doesn't require iteration over the list.

HTH
 
thanks! i was looking for more of a 1 line code response but i guess perl doesn't offer that as a valid solution.

thank you anyway for the great example!
 
What are you trying to do? If you want to search an array without using a loop, as in the example stevexff gave, you should consider using a hash.
 
i'm trying to keep the code super clean and supper efficient. .net has a one line search function for arrays and i was hoping lovely perl would have it too. ;)
 
In my experience, you rarely get clean and efficient together. I'm guessing here, but the .Net array search function probably loops through all the elements in the array behind the scenes anyway.

You can take a look at the grep function (perldoc -f grep) and see if it does what you're looking for.
 
I think rharsh is right on the money with grep!

Code:
    if ( grep { $_ eq 'yourmatchdata'} @array ) {
      # do something
    }

But that is just my 2 cents!
 
rharsh

Exactly the point I was trying to make. Just because you haven't had to code a loop, it doesn't mean that one isn't being executed somewhere on your behalf. BTW, the .NET example does iterate over all the items in the collection, although I think it stops when it finds one, rather than continuing to the end...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top