ArunMKumar ArunMKumar - 1 month ago 13
Perl Question

Regex matching with scalars in Perl.

To the moderators... READ THE QUESTION before marking as a duplicate.

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

#!/usr/bin/perl

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

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

else{

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.

and if you still think it is duplicate and wants to go to this question right here...

Detect exact string value of scalar in regex matching

please save your time and ego.. It is not the one, and it does not answer my query.. and please spare some time for this question till someone who genuinely wants to help answers this..

Answer

* is a quantifier, not a wildcard in Perl regexes. PM*C as a regex means P, followed by zero or more Ms, followed by C. For example, the following strings match it:

PC
PMC
PMMC
PMMMC
xxxPCxxx

If you need to match "anything", use .*.

Comments