Wednesday, 11 February 2015

Perl named capture containers, the coolest parsing trick ever.

Named capture containers only works in Perl 5.10 and up. In this example I am able to match lines in a log file by a key word. The tags like <time> become the key name in the hash %+.

Values can be extracted like you would with a normal hash.



while (<>) {
 $Line = $_;
 $Line =~ s/\n//;
 $Line =~ m/^(?<time>\d{10}.\d{3})\s*(?<status>connection)\s*(?<fd>\d*)\s*(?<ipaddress>\d*.\d*.\d*.\d).*/ ||
 $Line =~ m/^(?<time>\d{10}.\d{3})\s*(?<status>disconnect)\s*(?<fd>\d*).*/ ||
 $Line =~ m/^(?<time>\d{10}.\d{3})\s*(?<status>monitor)\s*(?<fd>\d*).*/;
 if(keys(%+) > 0) {
  foreach my $KeyName (keys %+) {
   $x{$KeyName} = $+{$KeyName};
  }
 }
}

No comments:

Post a Comment