Darren Birkett wrote:
Hi,

Hello,

Is there a better way to search all elements of an array for a string (without using a loop to test individual elements) than:

$line = join(' ',@myarray);
if ($line =~ /my string/) {
        some code
}

I've seen map and grep used by some but also critisized by some. I thought there might be a function to easily search all elements of an array at once for a string but I can't find one.

If all the elements are unique then use a hash.

if ( exists $hash{ 'my string' } ) {
    # do something
    }


The most efficient way to determine if an element exists in an array is to use a for loop and exit early:


my $found = 0;
for ( @array ) {
    if ( $_ eq 'my string' ) {
        $found = 1;
        last;
        }
    }


If you need to determine the number of matches you can use grep:

my $count = grep $_ eq 'my string', @array;



John
--
use Perl;
program
fulfillment

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>




Reply via email to