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

I am stuck on a program. I am working through a perl book and as an exercize in regular expressions it told me to create a regular expression that test tested for any number of backslashes followed by any number of asterisks. My if statement seems to return true for every string, regardless of whether it meets the desired criteria. I have researched and I have not found any examples that would help me fix my program. Here is my code:
#!/usr/bin/perl -w use strict ; while (<>) { if ($_ = /\\*\**/) { print "Your string has at least one a and any number of bs.\n" + ; last ; } else { print "Your string does not match.\n" ; last ; } }
*Ignore the response in the if statement. That was from an earlier program and I Just realized that I haven't updated it to say "Your string has zero or more \s and zero or more *s"

Replies are listed 'Best First'.
Re: Regular expression queston
by state-o-dis-array (Hermit) on Jun 19, 2012 at 22:32 UTC
    Hi Socrates440,

    Look closely at the if statement, something is missing, a single character near the = sign.

      state-o-dis-array:

      Nice catch--I totally missed the missing character.

      ...roboticus

      When your only tool is a hammer, all problems look like your thumb.

Re: Regular expression queston
by roboticus (Chancellor) on Jun 19, 2012 at 22:31 UTC

    Socrates440:

    Zero is a number, right? So *all* strings have any number of backslashes and any number of asterisks.

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

Re: Regular expression queston
by NetWallah (Canon) on Jun 19, 2012 at 22:37 UTC
    To get around what roboticus says, you need to match on MORE THAN zero characters - so consider using the "+" modifier, and ( (?:enable|alternation), or a [set-of-characters] ).

                 I hope life isn't a big joke, because I don't get it.
                       -SNL

      Ohhh so it did work. What is the missing character near the equals sign?
        The operator is "=~" . Since you are working with $_ anyway, you can actually delete the "$_ =" entirerly, since the regular expression match defaults to matching $_.

                     I hope life isn't a big joke, because I don't get it.
                           -SNL

Re: Regular expression queston
by Anonymous Monk on Jun 20, 2012 at 08:38 UTC
    since you are using *, which means 0 are more even if your doesnot match also it will return you true, So better go with +, And Use =~ whwnever you are using regular expression instead of = .