in reply to Regexp question

In addition to being conscious of the greedy behavior, it is also good practice to check that the match succeeded before using $1.

Replies are listed 'Best First'.
Re^2: Regexp question
by davidov0009 (Scribe) on Dec 20, 2007 at 17:35 UTC
    One last quick question. Is this valid for checking whether the match occurred, and would $1 be initialized to the matched text in this code?
    if ( $html =~ m/id="$element" name="challenge" value="(.*?)"/ ) { $post{$element} = $1; }

    use strict; use CGI;
      I believe so, but you can easily prove it for yourself with a trivial testcase.
      Yes, that'll work. As will
      $post{$element} = $1 if $html =~ m/id="$element" name="challenge" value="(.*?)"/;

      Unless you expect $element to contain metacharacters, you should use

      m/id="\Q$element\E" name="challenge" value="(.*?)"/;

      to escape any metacharacters in $html. See quotemeta for more.