Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Parsing file to pull out sections of text

by nitehawk (Initiate)
on Feb 03, 2009 at 17:30 UTC ( [id://741067]=perlquestion: print w/replies, xml ) Need Help??

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

Hi all, What I am trying to do is parse through a file formatted like below.
I want to go through the data, search for "d1", and take all of the data between "d1" and "d4" (inclusive) and place it in an array to do something interesting with later.
In the interest of brevity, I'll leave out the sordid details of what I've tried (although I'd be more than happy to provide it if it's helpful), but I keep getting stuck on how exactly to trigger getting a chunk of the file, and once finding the end trigger, to keep going through the rest of the file.
Thanks for any pointers :-)
source file (yes the source would have data separated by returns):
a b c d d1 d2 d3 d4 a b d1 d2 d4 a f g ...

Replies are listed 'Best First'.
Re: Parsing file to pull out sections of text
by toolic (Bishop) on Feb 03, 2009 at 18:05 UTC
    One way is to use Range Operators:
    use strict; use warnings; while (<DATA>) { print if (/d1/ .. /d4/); } __DATA__ a b c d d1 d2 d3 d4 a b d1 d2 d4 a f g

    prints:

    d1 d2 d3 d4 d1 d2 d4
Re: Parsing file to pull out sections of text
by DStaal (Chaplain) on Feb 03, 2009 at 17:46 UTC

    What have you tried? This looks like something fairly simple...

    Basically, I'd set a flag when I see d1, and unset it when I see d4. While the flag is set, push to the array. That's about three lines of code...

Re: Parsing file to pull out sections of text
by artist (Parson) on Feb 03, 2009 at 20:46 UTC
    use strict; use warnings; my $flag = 0; my $start = 'd1'; my $end = 'd4'; my @array; while (<DATA>) { chomp; if(/$start/){ $flag = 1; @array = (); } elsif(/$end/) { $flag = 0; print "@array\n"; } else{ push @array, $_ if $flag; } }
    --Artist
Re: Parsing file to pull out sections of text
by kennethk (Abbot) on Feb 03, 2009 at 17:43 UTC

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (5)
As of 2024-04-19 21:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found