Recursion was required...

#!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=921111 use warnings; my $sql = <<END; 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; END sub error { substr $_, pos($_), 0, "\e\[1;31;43m @_ \e[m"; die $_,"\n"; } print "ORIGINAL:\n\n$sql"; my $adding = ' format \\"%s|\\"'; # NOTE after each field name local $_ = $sql; selectexpr(); /\G;/gc or error 'incomplete parse'; print "\nMODIFIED:\n\n$_"; sub selectexpr { /\G\s*select/gc || error 'missing select'; do { /\G\s*(\w+)/gc ? do { # field name found my $pos = pos(); substr $_, $pos, 0, $adding; pos() = $pos + length $adding; } : /\G\s*\(/gc ? (selectexpr(), /\G\s*\)/gc || error 'missing close p +aren') : error 'either name or subselect expected'; } while /\G\s*,/gc; /\G\s*from/gc || error 'missing from'; /\G\s*\w+/gc || error 'missing table name'; /\G\s*where[^);]*/gc; # optional }

Outputs:

ORIGINAL: 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; MODIFIED: 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;

In reply to Re: Recursive parse - by tybalt89
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.