Created
June 13, 2011 14:38
-
-
Save jberger/1022879 to your computer and use it in GitHub Desktop.
Code pretty printer using Regexp::Grammars
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 strict; | |
use warnings; | |
use Data::Dumper; | |
use Regexp::Grammars; | |
my $grammar = qr{ | |
<nocontext:> | |
<Line> | |
<rule: Line> <[Element]>* | |
<rule: Element> <Words> | <Block> | <Command> | <Comment> | |
<rule: Command> <[Words]> ; | |
<rule: Block> \{ <[Element]>* \} | |
<rule: Comment> // .*? \s{2,} | |
<rule: Words> (?:\b\w+\b) ** \s | |
}x; | |
my $string = 'apple{{mango kiwi } guava ; banana; // pear berry;}'; | |
if ($string =~ $grammar) { | |
open my $log, ">", "log.txt"; | |
print $log Dumper \%/; #/ | |
print elements($/{Line}{Element}); | |
} else { | |
die "Did not match"; | |
} | |
sub elements { | |
my @elements = @{ shift() }; | |
my $indent = shift || 0; | |
my $output; | |
foreach my $element (@elements) { | |
$output .= "\t" x $indent; | |
foreach my $key (keys %$element) { | |
if ($key eq 'Words') { | |
$output .= $element->{$key} . "\n"; | |
} elsif ($key eq 'Block') { | |
$output .= "{\n" . elements($element->{$key}->{Element}, $indent + 1) . ("\t" x $indent) . "}\n"; | |
} elsif ($key eq 'Comment') { | |
$output .= $element->{$key} . "\n"; | |
} elsif ($key eq 'Command') { | |
$output .= join(" ", @{ $element->{$key}->{Words} }) . ";\n"; | |
} elsif ($key eq 'Element') { | |
$output .= elements($element->{$key}, $indent + 1); | |
} | |
} | |
} | |
return $output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment