Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

pattern matching issue =\

Status
Not open for further replies.

goliath

MIS
Aug 18, 1999
62
US
I'm sure you'd all get bored if I stopped posting my Perl troubles ;)

Here's a snippet of code I have which is plaguing me.

I am parsing a log file line by line, the first input works, the second does not work as I had hoped.

It seems it should be obvious...


Input:
[Mon May 13 20:05:51 2002] [58 Myrmidon] Oreck (Barbarian) <Dread Templar> ZONE: emeraldjungle
[Mon May 13 18:26:22 2002] [58 Myrmidon] Oreck (Barbarian) <Dread Templar>


Output:
Oreck,58,Warrior,Barbarian,emeraldjungle,Mon May 13 20:05:51 2002
Oreck,Oreck,,,,Mon May 13 18:26:22 2002


Code:

if ($line =~ m/Dread Templar/)
{
$line =~ m/^\[([\w\d\s]*:.*)\] \[.*/;
$date = $1;

$line =~ m/^\[.*\] \[.*\] ([A-Z,a-z,0-9]+) /;
$name = $1;

if ($line =~ m/^\[.*\] \[ANONYMOUS\] .*/)
{
print OUT &quot;$name,Anonymous,Anonymous,Anonymous,Anonymous,$date&quot;;
}
else
{
$line =~ m/^\[[\w\d\s]*:.*\] \[([\d]+) (\w+)\] \w+ \(([\w\s]+)\) <.*>\s*ZONE:\s*([a-z]+)/;
$number = $1;
$title = $2;
$class = $3;
$zone = $4;

}

print OUT &quot;$name,$number,$title,$class,$zone,$date&quot;;
}
print OUT &quot;\n&quot;;
}
}
 
The problem is the second line does not have the ZONE information. This causes the whole pattern match to fail. As a result, $number is set to the old $1 (Oreck) and since $2, $3, $4 are not set the other variables are empty. The following code will work for both lines:
Code:
@lines = (&quot;[Mon May 13 20:05:51 2002] [58 Myrmidon] Oreck (Barbarian) <Dread Templar> ZONE: emeraldjungle&quot;, &quot;[Mon May 13 18:26:22 2002] [58 Myrmidon] Oreck (Barbarian) <Dread Templar>&quot;);
foreach $line (@lines) {
    next unless ($line =~ m/\[(.+?)\]\s+\[(\d+)\s+\w+\]\s+(\w+)\s+\((\w+)\)\s+<Dread Templar>\s*\S*\s*(\w*)/);
    print &quot;$3,$2,Warrior,$4,$5,$1\n&quot;;
}
 
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Sponsor

Back
Top