Forum Moderators: coopster & phranque

Message Too Old, No Replies

Can't match string, even though I know it's there!

         

doctormelodious

2:47 am on Jun 29, 2004 (gmt 0)

10+ Year Member



Greetings,

I am working with the following code. (The character after the + signs is a lower case L. The character after that is the key above the TAB key.)


@nestedListPrefixes = ("++++l`","+++l`","++l`","+l`","l`");
$nestedListPrefixCount = $#nestedListPrefixes;

for ($i=0; $i<=$nestedListPrefixCount; $i++){
$listBegin = $nestedListPrefixes[$i];
.
.
.
}

The variable $theContent is from a form field, into which I've typed some text that includes the string "++++l`". Here's what I can't figure out. The first time through the loop, I test for the value of $listBegin with a debug line:

print ($listBegin eq "++++l`");

It returns "1".

I test the contents of $theContent:

print($theContent =~ /\+\+\+\+l`/);

It returns "1".

Yet, when I test this:

print($theContent =~ /$listBegin/);

It returns null.

If I change the test string to something without the + char, it works. So, Perl must be interpreting that + in some funky way. How do you make Perl match characters like that?

Thanks much!
Perry

kaled

9:31 am on Jun 29, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I'm new to Perl, but try the following

$listBegin = '\+\+\+\+l`/';
print($theContent =~ /$listBegin/);

The escape sequence is \+ is handled by the interpreter rather than translated by the compiler (I think).

Kaled.

coopster

11:22 am on Jun 29, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



An oft-referred tutorial here at WebmasterWorld:
Using Regular Expressions [etext.lib.virginia.edu]

timster

12:38 pm on Jun 29, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You're on the right track. When you hard-coded the pattern, you escaped the characters with special meanings. You have to do the same thing, even if the pattern is stored in a variable, like so:

for ($i=0; $i<=$nestedListPrefixCount; $i++){
$listBegin = $nestedListPrefixes[$i];

$listBegin=~s/(\W)/\\$1/g; # Escape non-word characters

print($theContent =~ /$listBegin/);
}

doctormelodious

11:01 pm on Jun 29, 2004 (gmt 0)

10+ Year Member



Thanks Timster,

That did the trick!

Perry