Last active
December 19, 2020 17:22
-
-
Save GoldsteinE/1c0d466682753b93c546e903d536499c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use v5.18; | |
use strict; | |
our %rules; | |
sub compile_rule { | |
state %compiled; | |
my $idx = shift; | |
return $compiled{$idx} if exists $compiled{$idx}; | |
my $rule = $rules{$idx}; | |
if ($rule =~ /^\"(.)\"$/) { | |
return $1; | |
} | |
my @parts = split /\s*\|\s*/, $rule; | |
my @compiled_parts; | |
foreach my $part (@parts) { | |
my @deps = split /\s+/, $part; | |
push @compiled_parts, (join '', map { compile_rule($_) } @deps); | |
} | |
my $res = join '|', @compiled_parts; | |
$res = "(?:$res)"; | |
$compiled{$idx} = $res; | |
$res | |
} | |
while (my $rule = <>) { | |
chomp $rule; | |
last unless $rule; | |
my ($idx, $body) = split /: /, $rule; | |
$rules{$idx} = $body; | |
} | |
my $reg = compile_rule 0; | |
say STDERR "Generated regex (@{[length $reg]} characters)"; | |
$reg = qr/^$reg$/; | |
my $count; | |
while (<>) { | |
$count++ if /$reg/; | |
} | |
say $count; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment