# define a string (scalar) variable
$a_string = 'Hello World';
# does the string contain the word 'Hello' in it?
if( [blue]index( $a_string, 'Hello' ) >= 0[/blue] ) {
print "It does!\n";
} else {
print "It doesn't\n";
}
Why use [tt]index()[/tt] rather than regexes? Three reasons:
1. It's the right tool for the job. Regexes are for matching patterns whereas this is just a straight search. This makes the intent of the programmer clearer which aids debugging and is a good thing.
2. It can be significantly faster.
3. Once incorporated into more complex code, it's unlikely that we'll just be looking for the pre-determined word 'Hello' - the second argument will probably be a variable. At that stage, we have to start worrying about quoting metacharacters or we'll get more than we bargained for (see multiple threads).
Yours,
fish
["]As soon as we started programming, we found to our surprise that it wasn't as easy to get programs right as we had thought. Debugging had to be discovered. I can remember the exact instant when I realized that a large part of my life from then on was going to be spent in finding mistakes in my own programs.["]
--Maur
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.