finding element in a array

i have aray
@test = ("java", "visual", "pascal", "cobol");

how do i find if the the element visual exists in array or not.

i know to do thru for loop, but do we have any function for arrays

Rahul
LVL 1
shahrahulbAsked:
Who is Participating?
 
ozoConnect With a Mentor Commented:
perldoc -q "How can I tell whether a certain element is contained in a list or array?"
0
 
shahrahulbAuthor Commented:
got it:

grep(/rahul/, @arr)
0
 
shahrahulbAuthor Commented:
Please close this question

Thanks.
0
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

 
gripeConnect With a Mentor Commented:
There is no way to do this without looping. You can use grep, but it does the same thing behind the scenes. This is also a faq (perldoc -q contains):

for (@test) { print "Match" if $_ eq "visual"; last;} # Find the match, and exit the loop
($is_there) = grep $_ eq "visual",  @test; # Bad practice, every element is checked regardless of whether the match is found.
0
 
gripeCommented:
shahrahulb,

grep is worse than looping. In a grep() every element of the array is checked whether it matches or not. if you do a for () {} loop, you can exit the loop before checking the remaining elements. (As above)
0
 
gripeCommented:
It's also even worse practice to do a regex match, since a regex match will be much slower than a standard string compare with 'eq'.

All of this is covered in the faq.
0
 
gripeConnect With a Mentor Commented:
Sorry, my example should read:

for (@test) {
    if ( $_ eq "visual" ) { print "Match"; last; }
}
0
 
ozoConnect With a Mentor Commented:
Although there is no way to do this without looping, you can loop only once, and then find multiple elements with no furthur loops

my %test;
@test{@test}=(1) x @test;

for( "visual","rahul" ){
   print "match $_\n" if $test{$_};
}

grep(/visual/, @arr) besides being slow, will also match if @arr contains somehing like "revisualizing"
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.