CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
How do I get everything between first and second match?

 



testerV
Novice

Nov 28, 2012, 7:20 PM

Post #1 of 5 (2294 views)
How do I get everything between first and second match? Can't Post

Hi!
How do I get everything between first and second match including matched lines?
I got this script but I stuck again with the “while” loop.
while (my $line = <$itf_fh>) {
next until $line =~ /^startA/;
print $tmpout_fh $line ;

while (<$itf_fh>) {
last if $line =~/^stopA/;
print $tmpout_fh $line; ;
}
}

Code



      
    


rovf
Veteran

Nov 29, 2012, 3:47 AM

Post #2 of 5 (2288 views)
Re: [testerV] How do I get everything between first and second match? [In reply to] Can't Post

If you get stuck in the inner "while", it must be because no line starting with 'stopA' is found.

However, you don't need the nested loops. Have a look at the operators .. (double dot) and ... (triple dot) in perldoc perlop
(see the section "Range Operators" - they have a coding example which might suit your needs).


testerV
Novice

Nov 29, 2012, 5:59 PM

Post #3 of 5 (2281 views)
Re: [rovf] How do I get everything between first and second match? [In reply to] Can't Post

Thank you Rovf!


Chris Charley
User

Nov 29, 2012, 6:04 PM

Post #4 of 5 (2281 views)
Re: [testerV] How do I get everything between first and second match? [In reply to] Can't Post

Using the double dot, .., operator that rovf mentioned, the code could be as follows.

Code
#!/usr/bin/perl 
use strict;
use warnings;

print grep /^startA/ .. /^stopA/, <DATA>;

__DATA__
one
line
startA
meat
of
the
data
stopA
nothing
here

Documentation for grep is here. Also, here is the documentation for the range (double dot) operator.


testerV
Novice

Dec 3, 2012, 1:04 PM

Post #5 of 5 (2262 views)
Re: [Chris Charley] How do I get everything between first and second match? [In reply to] Can't Post

Thanks Chris!
Grep will work but my file has 1.5 to 3 millions lines, so I'm not sure if I should use grep. I thought using <while> loop is safe way to use with a big file.
Thank you again!
testerV

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives