-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathIniReader.pm
142 lines (95 loc) · 2.7 KB
/
IniReader.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
package IniReader;
use strict;
use warnings;
use Carp;
use Data::Dumper;
my $DEBUG = 0;
sub new {
my $packagename = shift;
my ($filename) = @_;
my $self = { section_to_att_val => {}, # section -> att = value
};
open (my $fh, $filename) or confess "Error, cannot open file $filename";
my $conf_text = "";
while (<$fh>) {
if (/^[\:\#]/) { next; } ## comment line
unless (/\w/) { next; }
$conf_text .= $_;
}
$conf_text =~ s|\\\n||g;
$conf_text =~ s/ +/ /g;
print STDERR "CONF_TEXT:\n$conf_text\n" if $DEBUG;
my $current_section = "";
my @lines = split(/\n/, $conf_text);
for my $line (@lines) {
#print "ConfLine: $line\n";
if ($line =~ /^\[([^\]]+)\]/) {
$current_section = $1;
$current_section = &_trim_flank_ws($current_section);
print STDERR "Got section: $current_section\n" if $DEBUG;
}
elsif ($line =~ /^([^=]+)=(.*)$/) {
my $att = $1;
my $val = $2;
$att = &_trim_flank_ws($att);
$val = &_trim_flank_ws($val);
$self->{section_to_att_val}->{$current_section}->{$att} = $val;
print STDERR "ATT ($att) => VAL ($val)\n" if $DEBUG;
}
else {
print STDERR "Ignoring conf file line: $_\n" if $DEBUG;
}
}
close $fh;
bless ($self, $packagename);
return($self);
}
####
sub get_section_headings {
my $self = shift;
my @section_headings = keys %{$self->{section_to_att_val}};
return(@section_headings);
}
####
sub has_section_heading {
my $self = shift;
my ($heading) = @_;
if (exists $self->{section_to_att_val}->{$heading}) {
return(1);
}
else {
return(0);
}
}
####
sub get_section_attributes {
my $self = shift;
my $section = shift;
my @attributes = keys %{$self->{section_to_att_val}->{$section}};
return(@attributes);
}
####
sub get_value {
my $self = shift;
my ($section, $attribute) = @_;
return ($self->{section_to_att_val}->{$section}->{$attribute});
}
####
sub get_section_hash {
my $self = shift;
my ($section) = @_;
if (ref ($self->{section_to_att_val}->{$section}) eq 'HASH') {
return(%{$self->{section_to_att_val}->{$section}});
}
else {
print Dumper($self->{section_to_att_val});
confess "Error, no section values recorded for $section";
}
}
####
sub _trim_flank_ws {
my ($string) = @_;
$string =~ s/^\s+|\s+$//g;
return($string);
}
1; #EOM