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

I got useful help for my previous Question. But I am stuck when I have the following data
___DATA___ begin loop warn('xxx'); endloop; loop null; loop warn('AAA'); endloop; endloop; loop loop warn('BBB'); endloop; warn('rrr'); endloop; begin loop endloop; warn('yyy'); end; warn('zzz'); end;
I need to get
warn('xxx'); warn('AAA'); warn('BBB'); warn('rrr');
But I get only
warn('xxx'); warn('AAA'); warn('BBB');

Replies are listed 'Best First'.
Re: more regex help ...
by pg (Canon) on Nov 28, 2003 at 06:21 UTC

    Use a counter, when you see "loop", ++; when you see "endloop", --. when you see warn, and counter is greater than 0, take it.

    use strict; use warnings; my $count; while (my $line = <DATA>) { if ($line =~ m/endloop/) { $count --; } elsif ($line =~ m/loop/) {#don't put this before endloop, as end +loop itself matches loop $count ++; } elsif ($line =~ m/warn/) { print $line if ($count > 0); } } __DATA__ begin loop warn('xxx'); endloop; loop null; loop warn('AAA'); endloop; endloop; loop loop warn('BBB'); endloop; warn('rrr'); endloop; begin loop endloop; warn('yyy'); end; warn('zzz'); end;
Re: more regex help ...
by Zaxo (Archbishop) on Nov 28, 2003 at 06:26 UTC

    You have changed the requirement to include more complicated loop..endloop constructs. While there may be a regex that can dissect that, perhaps a parser is more what you need. Does your data have a grammar you can feed a parser generator like Parse::RecDescent or (b)yacc?

    After Compline,
    Zaxo

      Thanks every one for your help. I had a look at Parse::RecDescent, it looks too advanced for my requirement. I will try to understand it more before deciding on anything. Thanks again for all the help !!
Re: more regex help ...
by ysth (Canon) on Nov 28, 2003 at 06:22 UTC
    Then you need something like:
    my $loop=0; my $endloop=0; while (<>) { ++$loop if /\bloop\b/; ++$endloop if /\bendloop\b/; print if /\bwarn\b/ && $loop > $endloop; }
Re: more regex help ...
by Roger (Parson) on Nov 28, 2003 at 06:24 UTC
    use strict; my $nest; for (<DATA>) { $nest++ if /\bloop/; $nest-- if /\bendloop/; $nest && /warn/ && print } __DATA__ begin loop warn('xxx'); endloop; loop null; loop warn('AAA'); endloop; endloop; loop loop warn('BBB'); endloop; warn('rrr'); endloop; begin loop endloop; warn('yyy'); end; warn('zzz'); end;