In this case it's probably easier to use a stack and a loop rather than recursion. Consider:

use warnings; use strict; my $sql = <<SQL; select A, B, C, (select D, E, F, (select G, H from AA where ID = Z) from BB where ID2 = X), I, J from CC; SQL my @parts = split /(\W+)/, $sql; my @formatting = (undef); for my $part (@parts) { print $part; if (lc $part eq 'select') { $formatting[-1] = 1; next; } if (lc $part eq 'from') { $formatting[-1] = undef; next; } if ($part =~ m'\)') { pop @formatting; } next if ! $formatting[-1]; if ($part =~ m'\(') { push @formatting, undef; next; } print qq{ format \\"\%s|\\"} if $part =~ /\w/; }

Prints:

select A format \"%s|\", B format \"%s|\", C format \"%s|\", (select D format \"%s|\", E format \"%s|\", F format \"%s|\", (select G format \"%s|\", H format \"%s|\" from AA where ID = Z) f +rom BB where ID2 = X), I format \"%s|\", J format \"%s|\" from CC;
True laziness is hard work

In reply to Re: Recursive parse - by GrandFather
in thread Recursive parse - by real.aussie

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.