match leading '*' in r.e... how?

L

Leor Zolman

I'm probably going to feel really stupid when I see the answer, but I'm now
stuck nevertheless... I need to match a leading literal '*', and Perl isn't
getting the idea. Reading from standard input, typing "const" into the program
below yields "just const" as expected, but typing "*const" ALSO results in it
just saying "just const", rather than "*const".

This is a simplification of a much more complex r.e. where I need to detect an
asterisk immediately preceding "const", and it isn't working either.

How am I being brain-dead?
-leor

while (<>)
{
if (/const/)
{
print "just const\n\n";
}
elsif (/\*const/)
{
print "*const\n\n";
}
else
{
print "None.\n";
}
}
 
J

John Bokma

Leor said:
I'm probably going to feel really stupid when I see the answer, but I'm now
stuck nevertheless... I need to match a leading literal '*', and Perl isn't
getting the idea. Reading from standard input, typing "const" into the program
below yields "just const" as expected, but typing "*const" ALSO results in it
just saying "just const", rather than "*const".

This is a simplification of a much more complex r.e. where I need to detect an
asterisk immediately preceding "const", and it isn't working either.

How am I being brain-dead?
-leor

while (<>)
{
if (/const/)
{
print "just const\n\n";

Nope, /const/ matches *const, constant, fooconstbar etc.

Always print the thingy when debugging... Not a silly message which
assumes your program works (which it doesn't).
}
elsif (/\*const/)
{
print "*const\n\n";
}
else
{
print "None.\n";
}
}

To fix it: match the most specific one first. Also read how one can
create a "switch" in perl. It will quite likely make your code more
readable.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top