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 John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to find out if a value exists in array?

Status
Not open for further replies.

vane

Technical User
Apr 7, 2005
4
RO
I find myself doing something like this quite often:

foreach(@array) {
if ($_ == $value) {
$found=1;
last;
}
}

if ($found) {
# $value found in @array...
}

Is there a shorter/more elegant way to do this in perl?

 
A quick way:
Code:
@a  = ( 1,2,3,4,5,4,5,3,2,1 );
@found{@a} = @a;
foreach( sort keys %found ) {
  print "$_\n";
}
This uses a hash slice to acheive what you require. A hash has key value pairs, where the key is unique. So the hash slice assignment treats each element in @a as a key, and for this example, assigns an arbitrary value. What you end up with is the hash %found, whose keys are the unique elements of @a.
Cheers, Neil
 
thanks, but actually I only wanted to know if given value exists in an array. I would still have to iterate %found hash to find out if a given scalar exists, right?

Which is no problem of course, but I have always thought that a long piece of code only for that purpose... (In perl standards, perfectly understandable in other languages of course)
 
No, once you have the hash, you can use:
Code:
if( exists $hash{ $key } ) { ... }
Cheers, Neil :)
 
Or if you don't want to create the hash, use:
Code:
@a = qw( to be or not to be );
print "found!!\n" if scalar grep { $_ eq "not" } @a;
Cheers, Neil :)
 
Well that's a pretty piece of code... I will definitely use that one.

Thanks, Neil
 
Both methods are good, it seems to me, but for different applications.

If you're only searching through an array once, the grep approach seems appropriate.

If you're going to be repeatedly searching for values in an array it may well be worth the overhead of building a hash of the values to allow fast lookups. Mike
________________________________________________________________

"Experience is the comb that Nature gives us, after we are bald."

Is that a haiku?
I never could get the hang
of writing those things.
 
Do you mean that it's faster to iterate a hash than an array? Why so?
 
You don't have to iterate through a hash. The key is used to create a hash code - which is used to create a unique adress in memory. Therefore, $hash{"a"} goes straight to the adress in memory without having to loop through the entire hash. Makes for quick insertion and retrieval :)
Cheers, Neil
 
exactly so Mike
________________________________________________________________

"Experience is the comb that Nature gives us, after we are bald."

Is that a haiku?
I never could get the hang
of writing those things.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top