in reply to pattern matching (greedy, non-greedy,...)

Here is a solution which avoids the greediness issue by using a state variable and a line buffer:
use warnings; use strict; my $flag = 0; my @lines; while (<DATA>) { if (/KEY/) { @lines = (); $flag = 1; } if ($flag) { push @lines, $_; if (/PATTERN/) { print @lines; $flag = 0; } } } __DATA__ KEY blah blahblah KEY blah ah other random stuff KEY blah ha other random stuff PATTERN asdf KEY fdas PATTERN
prints:
KEY blah ha other random stuff PATTERN KEY fdas PATTERN

Replies are listed 'Best First'.
Re^2: pattern matching (greedy, non-greedy,...)
by ikegami (Patriarch) on Dec 17, 2009 at 02:22 UTC
    I was gonna suggest using the range op, but it doesn't really help
    my @lines; while (<DATA>) { my $is_key = /KEY/; @lines = () if $is_key; if (my $in_range = $is_key .. /PATTERN/) { push @lines, $_; print @lines if $in_range =~ /E0\z/; } }

    If one continues to simplify the above, one gets the parent's code.