I want to show you three ways. The first one illustrates how the second one works. The second one illustrates how the third one works. The first two are inefficient, but are sort of building blocks toward understanding the third. Here's the messy and inefficient way to do it. :)
sub test {
my $s = shift;
my $l = length $s;
if ($s =~ /[xyz]{$l}/) {
print "$s matches\n";
return;
}
print "$s doesn't match\n";
}
The principle is that you're repeating the character class [xyz] as many times as there are characters in the string using the '{n}' quantifier. Now here's a more efficient way that follows a similar principle, but eliminates the need for you doing the counting yourself.
sub test {
my $s = shift;
if ( $s =~ /^[xyz]+$/ ) {
print "$s matches\n";
return;
}
print "$s doesn't match\n";
}
Now the character class [xyz] must match each character from the start to the end of the string because of the '+' quantifier. We've introduced the ^ and $ assertions, which are telling the regexp that it can only match if the string starts and ends with a match, and since there's only one thing that can match, repeated a bunch of times with the + quantifier, it means that only a string containing nothing but a bunch of x's, y's, and z's will match. Think of the ^ and $ as stretching the + quantifier to fit from the beginning to the end of the string.
The problem with the first two methods is that you've got to match a character class repeatedly throughout every character of the string. This isn't particularly efficient. In fact, it's worse than you might imagine. It means that every time through the test, every character needs to be tested several ways.
There is yet another way to do it that is much more efficient:
sub test {
my $s = shift;
if ( $s =~ /[^xyz]/ ) {
print "$s contains non-xyz characters.\n";
return;
}
print "$s does not contain non-xyz characters.\n";
}
Notice that this method is a little backwards. Instead of focusing on whether the string contains something repeatedly from start to finish, this method focuses on whether anything BUT what we want exists within the string, by using a negated character class. No quantifier is needed, because we only care if there is even one existance of a dirty character (a non-xyz character). For the same reason, no ^ and $ is are needed. This will be a more efficient regexp, and probably the best choice. This match succeeds and terminates as soon as the first non-xyz character is found. That's a big win. Just be sure to understand the logic.
I hope this helps.
Dave
"If I had my life to do over again, I'd be a plumber." -- Albert Einstein |