Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: multi-line parsing

by jethro (Monsignor)
on Mar 31, 2009 at 18:47 UTC ( [id://754501]=note: print w/replies, xml ) Need Help??


in reply to multi-line parsing

Your problem is that you are reading the file line by line but expect three lines in your search pattern

There are a lot of ways you could do this, one would be to use a state machine. It uses a variable that notes which state it is in and depending on the next line switches to an appropriate state.

In this case state 1 means "I'm at the line after the first line I'm looking for" and state 2 means "I'm after the second line which followed the first line, expecting the number now"

#!/usr/bin/perl use strict; use warnings; my @array=(); open (INF, "$file"); my $state= 0; while (<INF>){ if ($state==0) { if (/^First line of text$/) { $state=1; } next; } if ($state==1) { if (/^second line of text$/) { $state=2; } elsif (/^First line of text$/) { $state=1; } else { $state=0; } next; } if ($state==2) { if (/^in the third line I have (\d*\.\d*)/) { push(@array,$1); $state=0; } elsif (/^First line of text$/) { $state=1; } else { $state=0; } next; } }

Note I used ^ and $ to denote line begin and end in the patterns so that the full lines must correspond to the pattern, not only a part of a line. Also used strict and warnings.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (3)
As of 2024-03-28 15:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found