WeBWorK Problems

Regex match capture

Re: Regex match capture

by Glenn Rice -
Number of replies: 0

First, remember that PG is not Perl.  PG is built on Perl, but modifies behavior to achieve convenience for problem authoring as well as security.  So there are always things to watch for.

One thing that you have already seen is the backslash that you need to use a double tilde for instead.

Another thing to watch for is code executed inside a BEGIN_TEXT/END_TEXT block.  Things do not always work as you expect.  If you add "warn match($num)" somewhere outside of the BEGIN_TEXT/END_TEXT block, you will see that the method is returning the correct thing.  What is happening here is that the PG parser inside the BEGIN_TEXT/END_TEXT block is messing with the $1 variable.  If you change your function to

sub match{
    my($foo)  = @_;
    my $test = $foo =~ /(5)/;
    if(!$test){return 0; }
    else{ return 1; }
}

or better

sub match{
    my($foo)  = @_;
    return $foo =~ /(5)/ ? 1 : 0;
}

it will work.

Even better than all of that is to switch to PGML and put this inside of [@ @]* in a BEGIN_PGML/END_PGML block.  Then it works as you have it.