in reply to Re: Metacharacters in regex expression
in thread Metacharacters in regex expression

Though I'd agree that index could be used, testing index's return value for truth is only useful in some circumstances. If $i isn't contained in $func_def, index returns -1, which is a true value, so your code will think it's been found. Similarly, if $i is at the start of the string (as the first example in yours is), index returns 0 (its position in the string), which is a false value.

In order to test if one string contains the other, you need to check that index returns >= 0.

Amended Code:
my $func_def = "char *strcmp(const char *s1, const char *s2)"; foreach my $i ('char *','const char.*','*') { if ( index( $func_def, $i ) >= 0 ) { print "'$func_def' contains '$i'\n"; } }

Replies are listed 'Best First'.
Re^3: Metacharacters in regex expression
by BrowserUk (Patriarch) on Sep 16, 2004 at 10:17 UTC

    A simple expedient for deriving a boolean value from index is to use 1+index(...). If the value is not found, you get 0. If it is found at the start of the string, you get 1.


    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail
    "Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon