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

a begin 1 <----- delete a <----- delete 2 <----- delete end c begin c end a begin 1
i want it to be
a begin end c begin c end a begin 1
i wrote my own code...but...it's to complex...
#!/usr/bin/perl use strict; use warnings; my @array = <DATA>; my $count = 0; my $fb = 0; foreach (@array) { if (/begin/) { $fb = $count; last; } $count++; } $fb++; my $count1; my $fc = 0; foreach (@array) { if (/end/) { $fc = $count1; last; } $count1++; } my $num = ($fc - $fb); splice (@array,$fb,$num); print @array; __DATA__ a begin 1 a 3 end c begin c end a begin 1
is there some simple way to do so? thanks!

Replies are listed 'Best First'.
Re: how to cut context between first "begin" and "end"?
by snoopy (Curate) on Sep 02, 2009 at 04:30 UTC
    One approach is to use a regular expression:
    #!/usr/bin/perl use common::sense; my $data = join('', <DATA>); $data =~ s{(^|\n)begin\n # begin at start of string or line (.*?\n)*? # lines to skip (non-greedy) end\n} # matching end {$1begin\nend\n}sx; print $data; __DATA__ a begin 1 a 2 end c begin c end a begin 1
    Update: added \n anchors and commented the regexp.
Re: how to cut context between first "begin" and "end"?
by jwkrahn (Abbot) on Sep 02, 2009 at 06:03 UTC
    $ echo "a begin 1 a 3 end c begin c end a begin 1" | perl -ne'print unless ?begin? .. ?end? and not /begin/ || /end/' a begin end c begin c end a begin 1
Re: how to cut context between first "begin" and "end"?
by spazm (Monk) on Sep 02, 2009 at 08:50 UTC
    from the command line:
    perl -pe '$skip=0 if /^end$/; next if $skip; $skip=1 if /^begin$/' dat +a.txt

    Or a little more drawn out:

    #!/usr/bin/perl use warnings; use strict; my $skip=0; while(<DATA>) { $skip=0 if /^end$; print unless $skip; $skip=1 if /^begin$/; } __DATA__ a begin 1 <----- delete a <----- delete 2 <----- delete end c begin c end a begin 1