Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

how to cut context between first "begin" and "end"?

by cxfcxf (Novice)
on Sep 02, 2009 at 04:12 UTC ( #792801=perlquestion: print w/ replies, xml ) Need Help??
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!

Comment on how to cut context between first "begin" and "end"?
Select or Download Code
Re: how to cut context between first "begin" and "end"?
by snoopy (Deacon) 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 (Monsignor) 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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://792801]
Approved by AnomalousMonk
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (19)
As of 2014-08-01 13:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Who would be the most fun to work for?















    Results (20 votes), past polls