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

Fellow Monks,

I have a problem that is really basic, but I'm having a hard time solving it.
I am trying to search a given string for the character *.
I have an if statement that calls a function to do some processing if 1 or more *'s are present in a string.

This is my approach:

if ($a =~ /\*/) { # call some function } else { # do something else }
But, for some reason, this isn't doing what I want. Can "someMonk" please help me out?

Thanks a bunch,
Tii

Replies are listed 'Best First'.
Re: Matching * in a pattern
by Nimster (Sexton) on Jul 26, 2000 at 09:55 UTC
    greping with scalar value returns the number of matches. Thus:
    $a = grep /\*/, $the_asterix_string;
    and $a would contain the number of *'s so you can call the function with it. you can still do
    if ($a) { : }
    since if there are no *'s, $a would be undef or 0. Doesnt matter which, if won't return true.

    -Nimster
    Freelance writer for GameSpy industries LTD. (www.gamespy.com)

      That's a fair idea Nimster, but here's an even better way.

      $num_matches = $str =~ tr/\*/\*/;

      Alakaboo
      I am the lurker that spams in the night.

Re: Matching * in a pattern
by turnstep (Parson) on Jul 26, 2000 at 06:34 UTC
    That should work. Can you give us more details on what is going wrong? Sample code and data - enough so we can duplicate the problem at least.
Re: Matching * in a pattern
by Tii (Monk) on Jul 26, 2000 at 16:46 UTC
    I looked at my code again and realized that it was doing what it was supposed to. It seems that the input files that I was reading from were changed without notice (which, I was told, was not going to happen).

    Thanks to all for the help...

    Tii

      Rule #1: Never, ever trust the user (or their data). Double check everything! :) That's one of the many reasons I love perl: it is so easy to write code that checks the format of any data it is receiving, or forces it change to the correct one, or only extracts the correct portion, or even sends an alarm when "bad" data is read in.

RE: Matching * in a pattern
by steveAZ98 (Monk) on Jul 26, 2000 at 07:26 UTC
    You might want to try the g flag, as it does a global match. More details would help.
    HTH
    $a =~ /\*/g;
    I've been informed by turnstep that this is not correct, please disregard.
    Thanks,
    Steve