in reply to Metacharacters in regex expression

If you always want $item to be treated like a literal string with no regex special characters, use the index function instead of a regex match:
my $func_def = "char *strcmp(const char *s1, const char *s2)"; foreach my $i ('char *','const char.*','*') { if (index($func_def,$i)) { print "'$func_def' contains '$i'\n"; } }
Update: ishnid is right; I didn't read the index documentation closely enough. Use his code instead. :) Thanks ishnid!

Replies are listed 'Best First'.
Re^2: Metacharacters in regex expression
by ishnid (Monk) on Sep 16, 2004 at 09:42 UTC
    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"; } }

      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