Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Is it possible to count the recursive depth as a whole recursive regex succeed ?
  • Comment on Possibility to count the recursive depth

Replies are listed 'Best First'.
Re: Possibility to count the recursive depth
by choroba (Cardinal) on Jan 05, 2022 at 15:37 UTC
    As Fletch mentioned, the trick is to use the (?{code}) assertion. Increment the current depth when entering the recursion (left parenthesis in the example), decrement it when leaving (right parenthesis). When incrementing, store the maximum.
    #!/usr/bin/perl use warnings; use strict; use feature qw{ say }; my $string = '((()))(((())))(()(()))'; my $max = 0; my $depth = 0; if ($string =~ /^( \( (?{$max = $depth if ++$depth > $max}) (?1)* \) (?{--$depth}) ) (?1)* $/gx ) { say $max; }

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
Re: Possibility to count the recursive depth
by Fletch (Bishop) on Jan 05, 2022 at 15:13 UTC

    How (Not) To Ask A Question

    I'd guess you could maybe do something with embedding something like (?{$depth++}) somewhere but lacking a concrete example to work from that's pure handwavium.

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.