0

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..

11
  • 1
    Your regex is wrong. "PM*C" matches a literal P, followed by 0-n letters M, followed by a C. So it would match PC, PMC, PMMC, PMMMMMC etc. Commented Oct 18, 2016 at 9:45
  • @PerlDuck thanks for that.. could you help me correct it? Commented Oct 18, 2016 at 9:46
  • 2
    @ArunMKumar A genuinuly well-meant comment -- please read up on basics. You got tripped by what * means in a regex. The whole topic is tricky, one has to go through basics first. Commented Oct 18, 2016 at 9:53
  • 5
    All your "READ THE QUESTION" and "please save your time and ego" comments aren't really going to encourage people to answer your question. You might consider removing those. Commented Oct 18, 2016 at 10:12
  • 2
    @ArunMKumar: I agree that your previous question shouldn't have need closed as a duplicate. I've reopened it and left a comment saying that. Commented Oct 18, 2016 at 10:42

1 Answer 1

2

* 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 .*.

Sign up to request clarification or add additional context in comments.

10 Comments

If you need to match "really anything", also add the /s flag. :-)
@ArunMKumar perldoc perlretut (look for "anchor").
@ArunMKumar: I'm not getting 1 from perl -lwe 'print "PM_MY_CALC_IS_FINE" =~ /PM.*C$/'
@ArunMKumar: Also note that $ has a special meaning in double quotes, switch to single quotes $regex = 'PM.*C$' or backslash it $regex = "PM.*C\$".
@ArunMKumar: I know it works. The important question is - do you understand why it works and your previous code doesn't?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.