-
Notifications
You must be signed in to change notification settings - Fork 7
/
BraceParser.pm
96 lines (83 loc) · 2.19 KB
/
BraceParser.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package BraceParser;
use vars qw($AUTOLOAD @ISA);
use Exporter;
use Carp;
use strict;
@ISA = qw(Exporter);
sub new {
my ($obj,$string) = @_;
my $pkg = ref($obj) || $obj;
my ($self,$dummystring) = get_contents("$string}");
bless $self,$pkg;
$self;
}
sub new_from_file {
my ($obj,$file) = @_;
local *FILE;
open FILE, $file or confess "Couldn't open $file: $!";
my $sep = $/;
undef $/;
my $string = <FILE>;
close FILE;
$/ = $sep;
new($obj,$string);
}
sub AUTOLOAD {
my $self = shift;
my $type = ref($self) || carp "Don't know about $self";
my $name = $AUTOLOAD;
# don't propagate DESTROY messages...
$name =~ /::DESTROY/ && return;
$name =~ s/.*://; #get only the bit we want
if (@_) { return $self->{$name} = shift }
else { return $self->{$name} }
}
sub name_contents_next {
my ($string) = @_;
$string =~ s/\n/ /g;
unless ($string =~ /\S/) { return () }
unless ($string =~ /\s*([^\{\}\s]+)\s*\{\s*(.*)/) { confess "Can't parse $string" }
my ($name,$contents);
($name,$string) = ($1,$2);
if ($string =~ /^\s*([^\{\}]*?)\s*\}(.*)/) {
($contents,$string) = ($1,$2);
} else {
($contents,$string) = get_contents($string);
}
($name,$contents,$string);
}
sub get_contents {
my ($string) = @_;
my ($contents,$subname,$subcontents);
$contents = {};
while (defined $string) {
($subname,$subcontents,$string) = name_contents_next($string);
push @{$contents->{$subname}}, $subcontents;
last if $string =~ s/^\s*\}\s*//;
}
($contents,$string);
}
sub print {
my ($self,$tree,$indent) = @_;
$tree = $self unless defined $tree;
$indent = 0 unless defined $indent;
my $firstline = 1;
my ($name,$contentslist,$contents);
while (($name,$contentslist) = each %$tree) {
foreach $contents (@$contentslist) {
unless ($firstline) { print " " x $indent }
else { $firstline = 0 }
if (ref $contents) {
my $text = "$name { ";
print $text;
my $oneline = $self->print($contents,$indent + length $text);
print " " x ($indent + length($text) - 2) unless $oneline;
print "}\n";
} else {
print "$name { $contents }\n";
}
}
}
$firstline;
}
1;