Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Determining if an element in a list

by shadox (Priest)
on Sep 13, 2001 at 01:51 UTC ( [id://112036]=note: print w/replies, xml ) Need Help??


in reply to Determining if an element in a list

Use the grep function, it searches for a pattern in a @list.
use warnings; use strict; my $pattern = '1'; my @list = ( 1,2,'a','b',5,1,1,'t'); # In a scalar context grep will return the total times # that the +pattern was find in @list # If you use @times = grep(/$pattern/,@list); # @times will contain the pattern it founds in the array # in this case @times will be ( 1 , 1 , 1 ) my $times = grep(/$pattern/,@list); print "The pattern was found $times times";

Replies are listed 'Best First'.
Re: Re: Determining if an element in a list
by davorg (Chancellor) on Sep 13, 2001 at 12:39 UTC

    In general, this is a pretty inefficient solution as you're searching the whole list every time. In the worst case you have a very long list and the element you're searching for is the first element.

    Something like thoe following is better:

    my $found; foreach (@list) { if (/$pattern/) { $found = 1; last; } }

    But the solutions in the FAQ are even better.

    --
    <http://www.dave.org.uk>

    Perl Training in the UK <http://www.iterative-software.com>

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (9)
As of 2024-03-28 18:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found