ArunMKumar ArunMKumar - 1 year ago 107
Perl Question

Regex matching by scalars in perl

I am using regular expression using scalars here. First time though. I will put the code. It should be self evident


my $regex = "PM*C";
my $var = "PM_MY_CALC";

if($var =~ m/$regex/){
print "match \n";


print "no match\n";

The output that I get is "no match"..

am i missing something obvious here? obviously It did not match any other stuff.. so just made both the regex and the variable to be checked equal.. still no match.

I have tried doing this too..

if($var =~ $regex ){

based on some search from perlMonks.

Answer Source

am i missing something obvious here?

You're missing how regular expressions work. They don't work how shell filename expansion works.

Your regex uses * which means "zero of more of the preceding character". So M* matches nothing, 'M', 'MM', 'MMM', etc.

You wanted to match "PM" followed by any number of any character followed by "C". The correct regex for that is PM.*C. A dot (.) means "match (almost) any character" and (as I said above) * matches zero or more of that.

I recommend reading the Perl Regular Expression tutorial.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download