On Jan 14, 2004, at 7:22 PM, 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

Since you've already been shown the super easy way, I'll dare to be a little different:


#!/usr/bin/perl

use strict;
use warnings;

$/ = '';                # enter "paragraph" mode
while (<>) {      # call with: perl script_name file1
        my %contact = map { /^(\w+):\s*(.+)$/ } split /\n/, $_;
        print "$_: $contact{$_}\n" foreach qw(Name City State);
        print "\n"
}

__END__

The first way your were shown is probably a little easier, but this method is probably better if you want to do anything more complicated than simple printing, since you have the whole hash to play with. It's a different way of thinking about the problem at least.

Good luck.

James


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