regexperlparsingregexp-grammars

Using a "normal" regex after loading Regexp::Grammars


I'm trying to use Regexp::Grammars in an application, but it breaks a lot of other regular expressions. For example, the following code:

$hello = 'hello';
print 'hello 1' if $hello =~ /hello/; #prints "hello 1"
use Regexp::Grammars;
print 'hello 2' if $hello =~ /hello/; #prints nothing

Demonstrates my problem. I'm not sure how to deal with this, except by loading and unloading the module repeatedly, and I'm not even sure I can use the extended regular expressions after I've explicitly unloaded the module with no. How do I allow normal regular expressions while still getting the power of Regexp::Grammars?


Solution

  • You can't unload a module. A module is just a script. To unload a module would be to unexecute it.

    However, this module does act as a lexical pragma, so you easily limit the scope of its effect.

    my $grammar = do {
        use Regexp::Grammars;
        qr{
            ...
        }x;
        # Active here
    };
    # Not active here
    

    The grammars created where Regexp::Grammars is active can be used where Regexp::Grammars isn't active, so just make Regexp::Grammars active only where a grammar is defined. (What a poor interface this module has!)

    If your code is poorly organised such that you need to disable Regexp::Grammars mid-scope, that too is possible by using

    no Regexp::Grammars;
    

    Note that the effect no Regexp::Grammars; is also lexically scoped.