--As off Wednesday, January 14, 2004 6:22 PM -0700, Jose Malacara is alleged to have said:

Can someone explain to me how to do multiline matching? I am trying
to extract three consecutive lines from a datafile containing
multiple records like this:

Name: Jose
City: Denver
State: Colorado
Address: 118 Mystreet
Age: 28



This is what I have so far, but it doesn't seem to work:

# !/usr/bin/perl -w
open FILE, "<file1" or die "Can't open file!\n";
while (<FILE>){
  if ( /^Name: (.*)\nCity: (.*)\nState: (.*)/) {
   print "Match found!\n";  # ideally, I want to print the the
lines found   }
}
close FILE;

But for some reason, it doesn't seem to like the (\n)'s in the
regex. Any help would be appreciated!

--As for the rest, it is mine.


You actually have two seperate problems here... First off, you aren't reading more than one line at a time, since the readline operator stops at a newline. Then, a regrex normally stops at a newline too, unless you specifically tell it to continue past those. ( The 'm' operator, mentioned in other posts.)

The first problem is actually the bigger one: The obvious solution of reading the whole file to an array/scalar first has preformance problems, especially with large files. (Worst case: A file bigger than avalible memory...)

Kent's solution neatly sidesteps that, if you don't care that the program has no idea of which records go together. (His solution just prints each record line, assuming they are in the correct order already.) Otherwise you are going to need some sort of temporary storage where you put the records back together, or read the file in chunks.

Daniel T. Staal

---------------------------------------------------------------
This email copyright the author.  Unless otherwise noted, you
are expressly allowed to retransmit, quote, or otherwise use
the contents for non-commercial purposes.  This copyright will
expire 5 years after the author's death, or in 30 years,
whichever is longer, unless such a period is in excess of
local copyright law.
---------------------------------------------------------------

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>




Reply via email to