On Wed, Jan 14, 2004 at 06:22:58PM -0700, Jose Malacara wrote:
> 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: Bob
> City: Austin
> State: Texas
> Address: 123 Whatever
> Age: 46 
> 
> 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!
> 
> This is what I would like to return:
> 
> Name: Bob
> City: Austin
> State: Texas
> 
> Name: Jose
> City: Denver
> State: Colorado

I'm sure others will have better solutions but this works -

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

while (<DATA>) {
    print if /^Name:/;
    print if /^City:/;
    print "$_\n" if /^State:/;
}

__DATA__
Name: Bob
City: Austin
State: Texas
Address: 123 Whatever
Age: 46

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

hth,
Kent

-- 
"I am always doing that which I can not do, 
   in order that I may learn how to do it." --Pablo Picasso


-- 
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