If you just want to match an exact string, using the index()builtin is faster:
my $word = 'dabchick';
if ( index $word, 'abc' >= 0 ) {
print 'Found 'abc' in $word\n';
}
But sometimes you want to match more or less of a particular string. That is when you use quantifi ers in your regular expression. For example, to match the letter a followed by an optional letter b, and then the letter c, use the ? quantifi er to show that the b is optional. The following matches both abc and ac:
if ( $word =~ /ab?c/ ) { ... }
The * shows that you can match zero or more of a given letter:
if ( $word =~ /ab*c/ ) { ... }
The + shows that you can match one or more of a given letter:
if ( $word =~ /ab+c/ ) { ... }
This sample code should make this clear. Use the qr() quote-like operator. This enables you to properly quote a regular expression without trying to match it to anything before you are ready.
You already know about the /x and /i modifi ers, so now look at the /g modifier. That enables you
to globally match something. For example, to print every non-number in a string, use this code:
my $string = '';
while ("a1b2c3dddd444eee66"=~/(\D+)/g ) {
$string .= $1;
}
print $string;
And that prints abcddddeee, as you expect.
You can also use this to count things, if you are so inclined