Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re^3: get n lines before a pattern

by VinsWorldcom (Vicar)
on Jul 25, 2012 at 15:16 UTC ( #983680=note: print w/ replies, xml ) Need Help??


in reply to Re^2: get n lines before a pattern
in thread get n lines before or after a pattern

Yes, the changes to the file in the OP certainly require an updated approach. What have you tried?

I would loop through the file saving each key and either pushing to a data structure if the name matches or resetting and continuing.

Pseudo code for the loop and structure I'd use:

my @matches; my $FOUND = 0; my %info = {}; while (<INFILE>) { chomp $_; if (($_ =~ /^id/) and ($FOUND)) { push @matches \%info; $FOUND = 0; %info = {} } if ($_ =~ /^id/) { (undef, $info{id}) = split / /, $_} if ($_ =~ /^address/) { (undef, $info{address}) = split / /, $_} if ($_ =~ /^name/) { (undef, $info{fname}) = split / /, $_} ... if ($searchPattern eq $info{fname}) { $FOUND = 1; } }

UPDATE: Added 'chomp' and updated 'split' commands as per kennethk suggestions to me.


Comment on Re^3: get n lines before a pattern
Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (6)
As of 2015-07-05 10:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (61 votes), past polls