in reply to Matching inconsistency in for loop

You are using m//g in a scalar context which means that each match starts off where the previous match ended. That is, each match is only going to succeed if either the previous match failed or if the requested match happens later in the string than the previous match.

This starting (and previous ending) position can be queried via pos($answer), and can even be set via pos($answer)= 0;

You should probably just drop the "g"s.

Also, you didn't always use \Q and \E which could also cause you problems (though it didn't appear to in this case).

        - tye (but my friends call me "Tye")
  • Comment on (tye)Re: Matching inconsistency in for loop

Replies are listed 'Best First'.
Re: (tye)Re: Matching inconsistency in for loop
by Rich36 (Chaplain) on Dec 13, 2001 at 02:04 UTC
    Thanks very much. That definitely helps me understand that. I've fixed the code so that I don't have to redefine the variable.
    The next thing I'm having difficulty with is figuring out how to match what's inbetween the questions.
    I'm trying to get
    $answer =~ /$questions[$i](.*)$questions[$j]/; print qq(The answer is $1);
    or some variation of that to work(/g, /gm, etc.), but I'm not having any luck. Would somebody be able to explain how I could get the answers out of the question set?
    Thanks, Rich
    Rich36
    There's more than one way to screw it up...

      if( $answer =~ /\Q$questions[$i]\E(.*?)\Q$questions[$j]\E/s ) { print qq(The answer is $1\n); }
      /m controls whether ^ and $ can match around newlines in the middle of the string. You want /s which controls whether . can match newlines.

              - tye (but my friends call me "Tye")
        You sir, are truly a saint. I've been tearing my hair out over that for some time. I've obviously got some learning to do when it comes to regular expressions.
        This problem is work related, but what I plan on doing is to reformat the code and set up a Snippet on extracting questions and answers from text.
        Thanks.
        Rich36
        There's more than one way to screw it up...