Home: Perl Programming Help: Advanced:
Reading / Parsing



adp
newbie

Oct 26, 2001, 10:33 AM


Views: 5117
Reading / Parsing

I am a beginner and need some help.
I am reading a directory files and looking for specific files (all the mary's) then I am trying to only print specific lines.

A file will contain the following
Name= Mary Joe
Birthdate= October 26 1976
Location= Canada
Drivers Licence=: 123456
Type of Car= GM
Safari Mini Van
Phone Number= 987-645-321
Address= 20 Street, Toronto, On
Special=: Use side door for special delivers.
All other
mail is to be delivered to front door.
Previous Address: Unknown
Expiry= December 2002.


Here is my code:

($dir) = @ARGV;

chdir $dir;

$i=0;
while ($nextFileName = * )
{
$fileNames $i++ =$nextFileName;
}

$j=0;
print "\n";

$search1= "Mary";


foreach $fileName (@fileNames)
{
if ($fileName= ~ /$search1/)
{
print "\n\n$fileName\n\n\n";
$j++;
open( NAMES, " $fileName " ) or die "can't open $fileName";
while ( NAMES )
{
if (/Name=/)
{
print $_;
}
if (/Location=/)
{
print $_;
}
if (/Type of car=/)
{
print $_;
}
if (/Special=/)
{
print $_;
}

}
close NAMES;

}

}


print "\n\nNumber of matches: $j \n\n";

----
My problem: how can i print the second line (if it exists)of info in the type of car and all the lines provised in the Special field?

i appreciate your help.


ps. why doesn't my program show all the curly brackets and triangle brackets?




rGeoffrey
User

Oct 27, 2001, 2:04 PM


Views: 5109
Re: Reading / Parsing

The car line was not working because in the script you had "car" while in the data file you had "Car". So I added the case insensitive 'i' flag to the regular expressions. To print the extra special lines we keep reading and printing until we find the next line. I am assuming that the next line will always be "Expiry=", so you might need to change that regex or the data to make it work.

Here is some code that works...


Code
#!/usr/local/bin/perl 

use strict;

my $dirname = '.';
my $search = 'mary';

opendir (DIR, $dirname) or die "could not open dir, $!\n";
my @files = sort map {"$dirname/$_" } grep { /$search/ } readdir DIR;
closedir DIR;

foreach my $fileName (@files) {
open( NAMES, $fileName ) or die "can't open $fileName, $!";
print "------------------\n";
while (<NAMES>) {
if (/Name=/i) {
print $_;
} elsif (/Location=/i) {
print $_;
} elsif (/Type of car=/i) {
print $_;
} elsif (/Special=/i) {
print $_;
while (<NAMES>) {
last if (/Expiry=/i);
print $_;
}
}
}
close NAMES;
}

print "------------------\n", "\n\nNumber of matches: ", scalar (@files), " \n\n";

PS. To make code samples look right on these pages it is best to put them in

Code

blocks. I have added the spaces inside the braces so it will appear here, but you will want to use them without the spaces.