http://www.perlmonks.org?node_id=183933


in reply to Regular Expressions: Call for Examples

Not simple dinky ones, but perhaps regexes that got you out of a bind, or were quite sneaky at what they did, ...

A couple of times recently I've used a "nested" regexp to pull off a bit of tricky substition. The "outer" regexp serves as a filter, and the "inner" regex, fired via /e, does a more targetted subsitution (or no substitution at all).

In the code below, the challenge was to turn words like "cowsCanFly" into "cows-can-fly".

$phrase = "NoMatch cowsCanFly sheepAreVeryCool NoMatch"; $phrase =~ s{ \b ( [a-z]+ (?:[A-Z][a-z]+)+ ) \b }{ my $word = $1; $word =~ s/([A-Z])/"-" . lc($1)/eg; $word; }gex; print $phrase, "\n";
When I first posted this fragment (in this node), there was some concern that the regex engine wasn't reentrant, and that I'd just gotten lucky. Perhaps, though I've done this a few times with 5.6.0 or later, and haven't run into any problems.

japhy, since you're now a regex UberLord, perhaps you can vet this approach for reentrancy issues.

Replies are listed 'Best First'.
Re: Re: Regular Expressions: Call for Examples
by japhy (Canon) on Jul 22, 2002 at 14:39 UTC
    There's no re-entry here. The regex engine has exited once the regex portion of the s/// ends. Once the right-hand side of the substitution is done, the regex engine starts again; it is not paused, though, it has stopped. Compare: "japhy" =~ m{.(?{ "perlmonk" =~ /./ }).}; Watch it explode.

    _____________________________________________________
    Jeff[japhy]Pinyan: Perl, regex, and perl hacker, who'd like a job (NYC-area)
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

      That segfaults for me on 5.005_03, and 5.6.0, but not on 5.6.1 or 5.8.0. It seems to be fixed between 5.7.0 and 5.7.1. The former segfaults, the latter doesn't.

      Abigail

        It died on my 5.6.1, but no matter -- just introduce some $1 in there, and it breaks on everything I have (5.8 included):
        "japhy" =~ m{ ( . (?{ "perl" =~ /(.)/; print $1 }) . ) (?{ print $1 }) }x

        _____________________________________________________
        Jeff[japhy]Pinyan: Perl, regex, and perl hacker, who'd like a job (NYC-area)
        s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;