Perl_Programmer1992 has asked for the wisdom of the Perl Monks concerning the following question:

#! /usr/bin/perl $what = "coa"; if($what =~ /comm?a/){ print "Matched"; }

Hi monks , I am currently reading about metacharacters , and as per definition the ? metacharacter should match the preceding character zero or 1 time , so that means above code should print "Matched" , but it's not , please correct me where I am wrong , and also I will be very thankful if you can also explain to me the other metacharacters like + , * , (.) and backreferences.

Replies are listed 'Best First'.
Re: Conceptual doubt in metacharacters : Beginner in perl
by haukex (Archbishop) on Jan 02, 2019 at 09:09 UTC
    I will be very thankful if you can also explain to me the other metacharacters like + , * , (.) and backreferences

    perlretut is a good start. For your question:

    coacomacommacommmacommmma
    /com?a/
    /com*a/
    /com+a/
    /co(mm)?a/
    /co(m|mmm)a/
    /com{2}a/
    /com{0,2}a/
    /com{2,3}a/
    /com{3,}a/

      Thanks a ton my friend ! , I will save this table and below code for future reference , "Thanks !" x 100 :-)

Re: Conceptual doubt in metacharacters : Beginner in perl
by Athanasius (Cardinal) on Jan 02, 2019 at 07:05 UTC

    Hello Perl_Programmer1992, and welcome to the Monastery!

    “The preceding character” means the single, immediately preceding character, in this case m. But the character before that — another m — is not present in the string held by the variable $what, so there is no match. If you change the regex to /com?a/, it matches.

    Other metacharacters: + matches one or more of the preceding character; * matches zero or more of the preceding character; . (dot) matches any one (single) character (except a newline). Parentheses () are used for capturing: reading from left to right, the captured strings are available in the special variables $1, $2, etc. See “Metacharacters” under perlre#The-Basics.

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      Thank for the explanation @Athanasius , so it means that the part of the pattern before the character(in this case 'm') should be same as the original string.

        I find Regexp::Debugger very convenient when trying to find why a regular expression matches or does not match.