PageRenderTime 61ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/trunk/misc_scripts/Config/General.pm

#
Perl | 1938 lines | 1373 code | 392 blank | 173 comment | 213 complexity | 2b3333319899888750248759cff808b6 MD5 | raw file
Possible License(s): Apache-2.0, CC-BY-SA-3.0, BSD-3-Clause, LGPL-2.0, BSD-3-Clause-No-Nuclear-License-2014

Large files files are truncated, but you can click here to view the full file

  1. #
  2. # Config::General.pm - Generic Config Module
  3. #
  4. # Purpose: Provide a convenient way for loading
  5. # config values from a given file and
  6. # return it as hash structure
  7. #
  8. # Copyright (c) 2000-2003 Thomas Linden <tom@daemon.de>.
  9. # All Rights Reserved. Std. disclaimer applies.
  10. # Artificial License, same as perl itself. Have fun.
  11. #
  12. # namespace
  13. package Config::General;
  14. use FileHandle;
  15. use File::Spec::Functions qw(splitpath file_name_is_absolute catfile catpath);
  16. use strict;
  17. use Carp;
  18. use Exporter;
  19. $Config::General::VERSION = "2.24";
  20. use vars qw(@ISA @EXPORT);
  21. @ISA = qw(Exporter);
  22. @EXPORT = qw(ParseConfig SaveConfig SaveConfigString);
  23. sub new {
  24. #
  25. # create new Config::General object
  26. #
  27. my($this, @param ) = @_;
  28. my $class = ref($this) || $this;
  29. # define default options
  30. my $self = {
  31. AllowMultiOptions => 1,
  32. MergeDuplicateOptions => 0,
  33. MergeDuplicateBlocks => 0,
  34. LowerCaseNames => 0,
  35. UseApacheInclude => 0,
  36. IncludeRelative => 0,
  37. AutoLaunder => 0,
  38. AutoTrue => 0,
  39. AutoTrueFlags => {
  40. true => '^(on|yes|true|1)$',
  41. false => '^(off|no|false|0)$',
  42. },
  43. DefaultConfig => {},
  44. level => 1,
  45. InterPolateVars => 0,
  46. ExtendedAccess => 0,
  47. SplitPolicy => 'guess', # also possible: whitespace, equalsign and custom
  48. SplitDelimiter => 0, # must be set by the user if SplitPolicy is 'custom'
  49. StoreDelimiter => 0, # will be set by me unless user uses 'custom' policy
  50. CComments => 1, # by default turned on
  51. StrictObjects => 1, # be strict on non-existent keys in OOP mode
  52. StrictVars => 1, # be strict on undefined variables in Interpolate mode
  53. Tie => "", # could be set to a perl module for tie'ing new hashes
  54. parsed => 0, # internal state stuff for variable interpolation
  55. upperkey => "",
  56. lastkey => "",
  57. prevkey => " ",
  58. };
  59. # create the class instance
  60. bless($self,$class);
  61. if ($#param >= 1) {
  62. # use of the new hash interface!
  63. my %conf = @param;
  64. # save the parameter list for ::Extended's new() calls
  65. $self->{Params} = \%conf;
  66. # be backwards compatible
  67. $self->{ConfigFile} = delete $conf{-file} if(exists $conf{-file});
  68. $self->{ConfigHash} = delete $conf{-hash} if(exists $conf{-hash});
  69. # store search path for relative configs, if any
  70. $self->{ConfigPath} = delete $conf{-ConfigPath} if(exists $conf{-ConfigPath});
  71. # store input, file, handle, or array
  72. $self->{ConfigFile} = delete $conf{-ConfigFile} if(exists $conf{-ConfigFile});
  73. $self->{ConfigHash} = delete $conf{-ConfigHash} if(exists $conf{-ConfigHash});
  74. # handle options which contains values we are needing (strings, hashrefs or the like)
  75. if (exists $conf{-String} ) {
  76. if ($conf{-String}) {
  77. $self->{StringContent} = $conf{-String};
  78. }
  79. delete $conf{-String};
  80. }
  81. if (exists $conf{-Tie}) {
  82. if ($conf{-Tie}) {
  83. $self->{Tie} = delete $conf{-Tie};
  84. $self->{DefaultConfig} = $self->_hashref();
  85. }
  86. }
  87. if (exists $conf{-FlagBits}) {
  88. if ($conf{-FlagBits} && ref($conf{-FlagBits}) eq "HASH") {
  89. $self->{FlagBits} = 1;
  90. $self->{FlagBitsFlags} = $conf{-FlagBits};
  91. }
  92. delete $conf{-FlagBits};
  93. }
  94. if (exists $conf{-DefaultConfig}) {
  95. if ($conf{-DefaultConfig} && ref($conf{-DefaultConfig}) eq "HASH") {
  96. $self->{DefaultConfig} = $conf{-DefaultConfig};
  97. }
  98. elsif ($conf{-DefaultConfig} && ref($conf{-DefaultConfig}) eq "") {
  99. $self->_read($conf{-DefaultConfig}, "SCALAR");
  100. $self->{DefaultConfig} = $self->_parse($self->_hashref(), $self->{content});
  101. $self->{content} = ();
  102. }
  103. delete $conf{-DefaultConfig};
  104. }
  105. # handle options which may either be true or false
  106. # allowing "human" logic about what is true and what is not
  107. foreach my $entry (keys %conf) {
  108. my $key = $entry;
  109. $key =~ s/^\-//;
  110. if (! exists $self->{$key}) {
  111. croak "Unknown parameter: $entry => \"$conf{$entry}\" (key: <$key>)\n";
  112. }
  113. if ($conf{$entry} =~ /$self->{AutoTrueFlags}->{true}/io) {
  114. $self->{$key} = 1;
  115. }
  116. elsif ($conf{$entry} =~ /$self->{AutoTrueFlags}->{false}/io) {
  117. $self->{$key} = 0;
  118. }
  119. else {
  120. # keep it untouched
  121. $self->{$key} = $conf{$entry};
  122. }
  123. }
  124. if ($self->{MergeDuplicateOptions}) {
  125. # override if not set by user
  126. if (! exists $conf{-AllowMultiOptions}) {
  127. $self->{AllowMultiOptions} = 0;
  128. }
  129. }
  130. }
  131. elsif ($#param == 0) {
  132. # use of the old style
  133. $self->{ConfigFile} = $param[0];
  134. }
  135. else {
  136. # this happens if $#param == -1,1 thus no param was given to new!
  137. $self->{config} = $self->_hashref();
  138. $self->{parsed} = 1;
  139. }
  140. # prepare the split delimiter if needed
  141. if ($self->{SplitPolicy} ne 'guess') {
  142. if ($self->{SplitPolicy} eq 'whitespace') {
  143. $self->{SplitDelimiter} = '\s+';
  144. $self->{StoreDelimiter} = " " if(!$self->{StoreDelimiter});
  145. }
  146. elsif ($self->{SplitPolicy} eq 'equalsign') {
  147. $self->{SplitDelimiter} = '\s*=\s*';
  148. $self->{StoreDelimiter} = " = " if(!$self->{StoreDelimiter});
  149. }
  150. elsif ($self->{SplitPolicy} eq 'custom') {
  151. if (! $self->{SplitDelimiter} ) {
  152. croak "SplitPolicy set to 'custom' but no SplitDelimiter set.\n";
  153. }
  154. }
  155. else {
  156. croak "Unsupported SplitPolicy: $self->{SplitPolicy}.\n";
  157. }
  158. }
  159. else {
  160. $self->{StoreDelimiter} = " " if(!$self->{StoreDelimiter});
  161. }
  162. if ($self->{InterPolateVars}) {
  163. #
  164. # we are blessing here again, to get into the ::InterPolated namespace
  165. # for inheriting the methods available overthere, which we doesn't have.
  166. #
  167. bless($self, "Config::General::Interpolated");
  168. eval {
  169. require Config::General::Interpolated;
  170. };
  171. if ($@) {
  172. croak $@;
  173. }
  174. # pre-compile the variable regexp
  175. $self->{regex} = $self->_set_regex();
  176. }
  177. # process as usual
  178. if (!$self->{parsed}) {
  179. if ($self->{DefaultConfig} && $self->{InterPolateVars}) {
  180. $self->{DefaultConfig} = $self->_interpolate_hash($self->{DefaultConfig}); # FIXME: _hashref() ?
  181. }
  182. if (exists $self->{StringContent}) {
  183. # consider the supplied string as config file
  184. $self->_read($self->{StringContent}, "SCALAR");
  185. $self->{config} = $self->_parse($self->{DefaultConfig}, $self->{content});
  186. }
  187. elsif (exists $self->{ConfigHash}) {
  188. if (ref($self->{ConfigHash}) eq "HASH") {
  189. # initialize with given hash
  190. $self->{config} = $self->{ConfigHash};
  191. $self->{parsed} = 1;
  192. }
  193. else {
  194. croak "Parameter -ConfigHash must be a hash reference!\n";
  195. }
  196. }
  197. elsif (ref($self->{ConfigFile}) eq "GLOB" || ref($self->{ConfigFile}) eq "FileHandle") {
  198. # use the file the glob points to
  199. $self->_read($self->{ConfigFile});
  200. $self->{config} = $self->_parse($self->{DefaultConfig}, $self->{content});
  201. }
  202. else {
  203. if ($self->{ConfigFile}) {
  204. # open the file and read the contents in
  205. $self->{configfile} = $self->{ConfigFile};
  206. if ( file_name_is_absolute($self->{ConfigFile}) ) {
  207. # look if is is an absolute path and save the basename if it is absolute
  208. my ($volume, $path, undef) = splitpath($self->{ConfigFile});
  209. $path =~ s#/$##; # remove eventually existing trailing slash
  210. $self->{ConfigPath} = [] unless $self->{ConfigPath};
  211. unshift @{$self->{ConfigPath}}, catpath($volume, $path, '');
  212. }
  213. $self->_open($self->{configfile});
  214. # now, we parse immdediately, getall simply returns the whole hash
  215. $self->{config} = $self->_hashref();
  216. $self->{config} = $self->_parse($self->{DefaultConfig}, $self->{content});
  217. }
  218. else {
  219. # hm, no valid config file given, so try it as an empty object
  220. $self->{config} = $self->_hashref();
  221. $self->{parsed} = 1;
  222. }
  223. }
  224. }
  225. #
  226. # Submodule handling. Parsing is already done at this point.
  227. #
  228. if ($self->{ExtendedAccess}) {
  229. #
  230. # we are blessing here again, to get into the ::Extended namespace
  231. # for inheriting the methods available overthere, which we doesn't have.
  232. #
  233. bless($self, "Config::General::Extended");
  234. eval {
  235. require Config::General::Extended;
  236. };
  237. if ($@) {
  238. croak $@;
  239. }
  240. }
  241. return $self;
  242. }
  243. sub getall {
  244. #
  245. # just return the whole config hash
  246. #
  247. my($this) = @_;
  248. return (exists $this->{config} ? %{$this->{config}} : () );
  249. }
  250. sub _open {
  251. #
  252. # open the config file
  253. #
  254. my($this, $configfile) = @_;
  255. my $fh = new FileHandle;
  256. if( ! -e $configfile && defined($this->{ConfigPath}) ) {
  257. # try to find the file within ConfigPath
  258. foreach my $dir (@{$this->{ConfigPath}}) {
  259. if( -e catfile($dir, $configfile) ) {
  260. $configfile = catfile($dir, $configfile);
  261. last; # found it
  262. };
  263. }
  264. }
  265. local ($/) = $/;
  266. unless ($/) {
  267. carp("\$/ (INPUT_RECORD_SEPARATOR) is undefined. Guessing you want a line feed character");
  268. $/ = "\n";
  269. }
  270. if (-e $configfile) {
  271. open $fh, "<$configfile" or croak "Could not open $configfile!($!)\n";
  272. binmode($fh);
  273. $this->_read($fh);
  274. }
  275. else {
  276. if (defined $this->{ConfigPath}) {
  277. croak "The file \"$configfile\" does not exist within ConfigPath: " . join(":", @{$this->{ConfigPath}}) . "!\n";
  278. }
  279. else {
  280. croak "The file \"$configfile\" does not exist!\n";
  281. }
  282. }
  283. }
  284. sub _read {
  285. #
  286. # store the config contents in @content
  287. #
  288. my($this, $fh, $flag) = @_;
  289. my(@stuff, @content, $c_comment, $longline, $hier, $hierend, @hierdoc);
  290. local $_;
  291. if ($flag && $flag eq "SCALAR") {
  292. if (ref($fh) eq "ARRAY") {
  293. @stuff = @{$fh};
  294. }
  295. else {
  296. @stuff = split "\n", $fh;
  297. }
  298. }
  299. else {
  300. @stuff = <$fh>;
  301. }
  302. foreach (@stuff) {
  303. if ($this->{AutoLaunder}) {
  304. m/^(.*)$/;
  305. $_ = $1;
  306. }
  307. chomp;
  308. if ($this->{CComments}) {
  309. # look for C-Style comments, if activated
  310. if (/(\s*\/\*.*\*\/\s*)/) {
  311. # single c-comment on one line
  312. s/\s*\/\*.*\*\/\s*//;
  313. }
  314. elsif (/^\s*\/\*/) {
  315. # the beginning of a C-comment ("/*"), from now on ignore everything.
  316. if (/\*\/\s*$/) {
  317. # C-comment end is already there, so just ignore this line!
  318. $c_comment = 0;
  319. }
  320. else {
  321. $c_comment = 1;
  322. }
  323. }
  324. elsif (/\*\//) {
  325. if (!$c_comment) {
  326. warn "invalid syntax: found end of C-comment without previous start!\n";
  327. }
  328. $c_comment = 0; # the current C-comment ends here, go on
  329. s/^.*\*\///; # if there is still stuff, it will be read
  330. }
  331. next if($c_comment); # ignore EVERYTHING from now on, IF it IS a C-Comment
  332. }
  333. if ($hier) {
  334. # inside here-doc, only look for $hierend marker
  335. if (/^(\s*)\Q$hierend\E\s*$/) {
  336. my $indent = $1; # preserve indentation
  337. $hier .= " " . chr(182); # append a "?" to the here-doc-name, so
  338. # _parse will also preserver indentation
  339. if ($indent) {
  340. foreach (@hierdoc) {
  341. s/^$indent//; # i.e. the end was: " EOF" then we remove " " from every here-doc line
  342. $hier .= $_ . "\n"; # and store it in $hier
  343. }
  344. }
  345. else {
  346. $hier .= join "\n", @hierdoc; # there was no indentation of the end-string, so join it 1:1
  347. }
  348. push @{$this->{content}}, $hier; # push it onto the content stack
  349. @hierdoc = ();
  350. undef $hier;
  351. undef $hierend;
  352. }
  353. else {
  354. # everything else onto the stack
  355. push @hierdoc, $_;
  356. }
  357. next;
  358. }
  359. ###
  360. ### non-heredoc entries from now on
  361. ##
  362. # Remove comments and empty lines
  363. s/(?<!\\)#.+$//;
  364. next if /^\s*#/;
  365. next if /^\s*$/;
  366. # remove the \ char in front of masked "#", if any
  367. s/\\#/#/g;
  368. # look for here-doc identifier
  369. if ($this->{SplitPolicy} eq 'guess') {
  370. if (/^\s*(\S+?)(\s*=\s*|\s+)<<\s*(.+?)\s*$/) {
  371. $hier = $1; # the actual here-doc variable name
  372. $hierend = $3; # the here-doc identifier, i.e. "EOF"
  373. next;
  374. }
  375. }
  376. else {
  377. # no guess, use one of the configured strict split policies
  378. if (/^\s*(\S+?)($this->{SplitDelimiter})<<\s*(.+?)\s*$/) {
  379. $hier = $1; # the actual here-doc variable name
  380. $hierend = $3; # the here-doc identifier, i.e. "EOF"
  381. next;
  382. }
  383. }
  384. # look for multiline option, indicated by a trailing backslash
  385. if (/\\$/) {
  386. chop;
  387. s/^\s*//;
  388. $longline .= $_;
  389. next;
  390. }
  391. ###
  392. ### any "normal" config lines from now on
  393. ###
  394. if ($longline) {
  395. # previous stuff was a longline and this is the last line of the longline
  396. s/^\s*//;
  397. $longline .= $_;
  398. push @{$this->{content}}, $longline; # push it onto the content stack
  399. undef $longline;
  400. next;
  401. }
  402. else {
  403. # look for include statement(s)
  404. my $incl_file;
  405. if (/^\s*<<include\s+(.+?)>>\s*$/i || (/^\s*include\s+(.+?)\s*$/i && $this->{UseApacheInclude})) {
  406. $incl_file = $1;
  407. if ( $this->{IncludeRelative} && $this->{configpath} && !file_name_is_absolute($incl_file) ) {
  408. # include the file from within location of $this->{configfile}
  409. $this->_open( $incl_file );
  410. }
  411. else {
  412. # include the file from within pwd, or absolute
  413. $this->_open($incl_file);
  414. }
  415. }
  416. else {
  417. # standard entry, (option = value)
  418. push @{$this->{content}}, $_;
  419. }
  420. }
  421. }
  422. return 1;
  423. }
  424. sub _parse {
  425. #
  426. # parse the contents of the file
  427. #
  428. my($this, $config, $content) = @_;
  429. my(@newcontent, $block, $blockname, $grab, $chunk,$block_level);
  430. local $_;
  431. my $indichar = chr(182); # ?, inserted by _open, our here-doc indicator
  432. foreach (@{$content}) { # loop over content stack
  433. chomp;
  434. $chunk++;
  435. $_ =~ s/^\s*//; # strip spaces @ end and begin
  436. $_ =~ s/\s*$//;
  437. #
  438. # build option value assignment, split current input
  439. # using whitespace, equal sign or optionally here-doc
  440. # separator (ascii 182).
  441. my ($option,$value);
  442. if (/$indichar/) {
  443. ($option,$value) = split /\s*$indichar\s*/, $_, 2; # separated by heredoc-finding in _open()
  444. }
  445. else {
  446. if ($this->{SplitPolicy} eq 'guess') {
  447. # again the old regex. use equalsign SplitPolicy to get the
  448. # 2.00 behavior. the new regexes were too odd.
  449. ($option,$value) = split /\s*=\s*|\s+/, $_, 2;
  450. }
  451. else {
  452. # no guess, use one of the configured strict split policies
  453. ($option,$value) = split /$this->{SplitDelimiter}/, $_, 2;
  454. }
  455. }
  456. if ($value && $value =~ /^"/ && $value =~ /"$/) {
  457. $value =~ s/^"//; # remove leading and trailing "
  458. $value =~ s/"$//;
  459. }
  460. if (! defined $block) { # not inside a block @ the moment
  461. if (/^<([^\/]+?.*?)>$/) { # look if it is a block
  462. $block = $1; # store block name
  463. ($grab, $blockname) = split /\s\s*/, $block, 2; # is it a named block? if yes, store the name separately
  464. if ($blockname) {
  465. $block = $grab;
  466. }
  467. if ($this->{InterPolateVars}) {
  468. # interpolate block(name), add "<" and ">" to the key, because
  469. # it is sure that such keys does not exist otherwise.
  470. $block = $this->_interpolate("<$block>", $block);
  471. if ($blockname) {
  472. $blockname = $this->_interpolate("<$blockname>", $blockname);
  473. }
  474. }
  475. $block = lc($block) if $this->{LowerCaseNames}; # only for blocks lc(), if configured via new()
  476. $this->{level} += 1;
  477. undef @newcontent;
  478. next;
  479. }
  480. elsif (/^<\/(.+?)>$/) { # it is an end block, but we don't have a matching block!
  481. croak "EndBlock \"<\/$1>\" has no StartBlock statement (level: $this->{level}, chunk $chunk)!\n";
  482. }
  483. else { # insert key/value pair into actual node
  484. $option = lc($option) if $this->{LowerCaseNames};
  485. if (exists $config->{$option}) {
  486. if ($this->{MergeDuplicateOptions}) {
  487. $config->{$option} = $this->_parse_value($option, $value);
  488. }
  489. else {
  490. if (! $this->{AllowMultiOptions} ) {
  491. # no, duplicates not allowed
  492. croak "Option \"$option\" occurs more than once (level: $this->{level}, chunk $chunk)!\n";
  493. }
  494. else {
  495. # yes, duplicates allowed
  496. if (ref($config->{$option}) ne "ARRAY") { # convert scalar to array
  497. my $savevalue = $config->{$option};
  498. delete $config->{$option};
  499. push @{$config->{$option}}, $savevalue;
  500. }
  501. eval {
  502. # check if arrays are supported by the underlying hash
  503. my $i = scalar @{$config->{$option}};
  504. };
  505. if ($@) {
  506. $config->{$option} = $this->_parse_value($option, $value);
  507. }
  508. else {
  509. push @{$config->{$option}}, $this->_parse_value($option, $value); # it's already an array, just push
  510. }
  511. }
  512. }
  513. }
  514. else {
  515. $config->{$option} = $this->_parse_value($option, $value); # standard config option, insert key/value pair into node
  516. }
  517. }
  518. }
  519. elsif (/^<([^\/]+?.*?)>$/) { # found a start block inside a block, don't forget it
  520. $block_level++; # $block_level indicates wether we are still inside a node
  521. push @newcontent, $_; # push onto new content stack for later recursive call of _parse()
  522. }
  523. elsif (/^<\/(.+?)>$/) {
  524. if ($block_level) { # this endblock is not the one we are searching for, decrement and push
  525. $block_level--; # if it is 0, then the endblock was the one we searched for, see below
  526. push @newcontent, $_; # push onto new content stack
  527. }
  528. else { # calling myself recursively, end of $block reached, $block_level is 0
  529. if ($blockname) { # a named block, make it a hashref inside a hash within the current node
  530. $this->_savelast($blockname);
  531. $config->{$block} = $this->_hashref() # Make sure that the hash is not created implicitely
  532. unless exists $config->{$block};
  533. if (exists $config->{$block}->{$blockname}) { # the named block already exists, make it an array
  534. if ($this->{MergeDuplicateBlocks}) {
  535. # just merge the new block with the same name as an existing one into
  536. # this one.
  537. $config->{$block}->{$blockname} = $this->_parse($config->{$block}->{$blockname}, \@newcontent);
  538. }
  539. else {
  540. if (! $this->{AllowMultiOptions}) {
  541. croak "Named block \"<$block $blockname>\" occurs more than once (level: $this->{level}, chunk $chunk)!\n";
  542. }
  543. else { # preserve existing data
  544. my $savevalue = $config->{$block}->{$blockname};
  545. delete $config->{$block}->{$blockname};
  546. my @ar;
  547. if (ref $savevalue eq "ARRAY") {
  548. push @ar, @{$savevalue}; # preserve array if any
  549. }
  550. else {
  551. push @ar, $savevalue;
  552. }
  553. push @ar, $this->_parse( $this->_hashref(), \@newcontent); # append it
  554. $config->{$block}->{$blockname} = \@ar;
  555. }
  556. }
  557. }
  558. elsif (ref($config->{$block}) eq "ARRAY") {
  559. croak "Cannot add named block <$block $blockname> to hash! Block <$block> occurs more than once.\n"
  560. ."Turn on -MergeDuplicateBlocks or make sure <$block> occurs only once in the config.\n";
  561. }
  562. else {
  563. # the first occurence of this particular named block
  564. #### $config->{$block}->{$blockname} = $this->_parse($config->{$block}->{$blockname}, \@newcontent);
  565. $config->{$block}->{$blockname} = $this->_parse($this->_hashref(), \@newcontent);
  566. }
  567. $this->_backlast($blockname);
  568. }
  569. else { # standard block
  570. $this->_savelast($block);
  571. if (exists $config->{$block}) { # the block already exists, make it an array
  572. if ($this->{MergeDuplicateBlocks}) {
  573. # just merge the new block with the same name as an existing one into
  574. # this one.
  575. $config->{$block} = $this->_parse($config->{$block}, \@newcontent);
  576. }
  577. else {
  578. if (! $this->{AllowMultiOptions}) {
  579. croak "Block \"<$block>\" occurs more than once (level: $this->{level}, chunk $chunk)!\n";
  580. }
  581. else {
  582. my $savevalue = $config->{$block};
  583. delete $config->{$block};
  584. my @ar;
  585. if (ref $savevalue eq "ARRAY") {
  586. push @ar, @{$savevalue};
  587. }
  588. else {
  589. push @ar, $savevalue;
  590. }
  591. push @ar, $this->_parse( $this->_hashref(), \@newcontent);
  592. $config->{$block} = \@ar;
  593. }
  594. }
  595. }
  596. else {
  597. # the first occurence of this particular block
  598. #### $config->{$block} = $this->_parse($config->{$block}, \@newcontent);
  599. $config->{$block} = $this->_parse($this->_hashref(), \@newcontent);
  600. }
  601. $this->_backlast($block);
  602. }
  603. undef $blockname;
  604. undef $block;
  605. $this->{level} -= 1;
  606. next;
  607. }
  608. }
  609. else { # inside $block, just push onto new content stack
  610. push @newcontent, $_;
  611. }
  612. }
  613. if ($block) {
  614. # $block is still defined, which means, that it had
  615. # no matching endblock!
  616. croak "Block \"<$block>\" has no EndBlock statement (level: $this->{level}, chunk $chunk)!\n";
  617. }
  618. return $config;
  619. }
  620. sub _savelast {
  621. my($this, $key) = @_;
  622. $this->{upperkey} = $this->{lastkey};
  623. $this->{lastkey} = $this->{prevkey};
  624. $this->{prevkey} = $key;
  625. }
  626. sub _backlast {
  627. my($this, $key) = @_;
  628. $this->{prevkey} = $this->{lastkey};
  629. $this->{lastkey} = $this->{upperkey};
  630. }
  631. sub _parse_value {
  632. #
  633. # parse the value if value parsing is turned on
  634. # by either -AutoTrue and/or -FlagBits
  635. # otherwise just return the given value unchanged
  636. #
  637. my($this, $option, $value) =@_;
  638. # avoid "Use of uninitialized value"
  639. $value = '' unless defined $value;
  640. if ($this->{InterPolateVars}) {
  641. $value = $this->_interpolate($option, $value);
  642. }
  643. # make true/false values to 1 or 0 (-AutoTrue)
  644. if ($this->{AutoTrue}) {
  645. if ($value =~ /$this->{AutoTrueFlags}->{true}/io) {
  646. $value = 1;
  647. }
  648. elsif ($value =~ /$this->{AutoTrueFlags}->{false}/io) {
  649. $value = 0;
  650. }
  651. }
  652. # assign predefined flags or undef for every flag | flag ... (-FlagBits)
  653. if ($this->{FlagBits}) {
  654. if (exists $this->{FlagBitsFlags}->{$option}) {
  655. my %__flags = map { $_ => 1 } split /\s*\|\s*/, $value;
  656. foreach my $flag (keys %{$this->{FlagBitsFlags}->{$option}}) {
  657. if (exists $__flags{$flag}) {
  658. $__flags{$flag} = $this->{FlagBitsFlags}->{$option}->{$flag};
  659. }
  660. else {
  661. $__flags{$flag} = undef;
  662. }
  663. }
  664. $value = \%__flags;
  665. }
  666. }
  667. return $value;
  668. }
  669. sub NoMultiOptions {
  670. #
  671. # turn AllowMultiOptions off, still exists for backward compatibility.
  672. # Since we do parsing from within new(), we must
  673. # call it again if one turns NoMultiOptions on!
  674. #
  675. croak "The NoMultiOptions() method is deprecated. Set 'AllowMultiOptions' to 'no' instead!";
  676. }
  677. sub save {
  678. #
  679. # this is the old version of save() whose API interface
  680. # has been changed. I'm very sorry 'bout this.
  681. #
  682. # I'll try to figure out, if it has been called correctly
  683. # and if yes, feed the call to Save(), otherwise croak.
  684. #
  685. my($this, $one, @two) = @_;
  686. if ( (@two && $one) && ( (scalar @two) % 2 == 0) ) {
  687. # @two seems to be a hash
  688. my %h = @two;
  689. $this->save_file($one, \%h);
  690. }
  691. else {
  692. croak "The save() method is deprecated. Use the new save_file() method instead!";
  693. }
  694. }
  695. sub save_file {
  696. #
  697. # save the config back to disk
  698. #
  699. my($this, $file, $config) = @_;
  700. my $fh = new FileHandle;
  701. my $config_string;
  702. if (!$file) {
  703. croak "Filename is required!";
  704. }
  705. else {
  706. open $fh, ">$file" or croak "Could not open $file!($!)\n";
  707. if (!$config) {
  708. if (exists $this->{config}) {
  709. $config_string = $this->_store(0, %{$this->{config}});
  710. }
  711. else {
  712. croak "No config hash supplied which could be saved to disk!\n";
  713. }
  714. }
  715. else {
  716. $config_string = $this->_store(0,%{$config});
  717. }
  718. if ($config_string) {
  719. print $fh $config_string;
  720. }
  721. else {
  722. # empty config for whatever reason, I don't care
  723. print $fh "";
  724. }
  725. close $fh;
  726. }
  727. }
  728. sub save_string {
  729. #
  730. # return the saved config as a string
  731. #
  732. my($this, $config) = @_;
  733. if (!$config || ref($config) ne "HASH") {
  734. if (exists $this->{config}) {
  735. return $this->_store(0, %{$this->{config}});
  736. }
  737. else {
  738. croak "No config hash supplied which could be saved to disk!\n";
  739. }
  740. }
  741. else {
  742. return $this->_store(0, %{$config});
  743. }
  744. }
  745. sub _store {
  746. #
  747. # internal sub for saving a block
  748. #
  749. my($this, $level, %config) = @_;
  750. local $_;
  751. my $indent = " " x $level;
  752. my $config_string;
  753. foreach my $entry (sort keys %config) {
  754. if (ref($config{$entry}) eq "ARRAY") {
  755. foreach my $line (@{$config{$entry}}) {
  756. if (ref($line) eq "HASH") {
  757. $config_string .= $this->_write_hash($level, $entry, $line);
  758. }
  759. else {
  760. $config_string .= $this->_write_scalar($level, $entry, $line);
  761. }
  762. }
  763. }
  764. elsif (ref($config{$entry}) eq "HASH") {
  765. $config_string .= $this->_write_hash($level, $entry, $config{$entry});
  766. }
  767. else {
  768. $config_string .= $this->_write_scalar($level, $entry, $config{$entry});
  769. }
  770. }
  771. return $config_string;
  772. }
  773. sub _write_scalar {
  774. #
  775. # internal sub, which writes a scalar
  776. # it returns it, in fact
  777. #
  778. my($this, $level, $entry, $line) = @_;
  779. my $indent = " " x $level;
  780. my $config_string;
  781. if ($line =~ /\n/) {
  782. # it is a here doc
  783. my $delimiter;
  784. my $tmplimiter = "EOF";
  785. while (!$delimiter) {
  786. # create a unique here-doc identifier
  787. if ($line =~ /$tmplimiter/s) {
  788. $tmplimiter .= "%";
  789. }
  790. else {
  791. $delimiter = $tmplimiter;
  792. }
  793. }
  794. my @lines = split /\n/, $line;
  795. $config_string .= $indent . $entry . $this->{StoreDelimiter} . "<<$delimiter\n";
  796. foreach (@lines) {
  797. $config_string .= $indent . $_ . "\n";
  798. }
  799. $config_string .= $indent . "$delimiter\n";
  800. }
  801. else {
  802. # a simple stupid scalar entry
  803. $line =~ s/#/\\#/g;
  804. $config_string .= $indent . $entry . $this->{StoreDelimiter} . $line . "\n";
  805. }
  806. return $config_string;
  807. }
  808. sub _write_hash {
  809. #
  810. # internal sub, which writes a hash (block)
  811. # it returns it, in fact
  812. #
  813. my($this, $level, $entry, $line) = @_;
  814. my $indent = " " x $level;
  815. my $config_string;
  816. $config_string .= $indent . "<" . $entry . ">\n";
  817. $config_string .= $this->_store($level + 1, %{$line});
  818. $config_string .= $indent . "</" . $entry . ">\n";
  819. return $config_string
  820. }
  821. sub _hashref {
  822. #
  823. # return a probably tied new empty hash ref
  824. #
  825. my($this) = @_;
  826. my ($package, $filename, $line, $subroutine, $hasargs,
  827. $wantarray, $evaltext, $is_require, $hints, $bitmask) = caller(0);
  828. if ($this->{Tie}) {
  829. eval {
  830. eval "require $this->{Tie}";
  831. };
  832. if ($@) {
  833. croak "Could not create a tied hash of type: " . $this->{Tie} . ": " . $@;
  834. }
  835. my %hash;
  836. tie %hash, $this->{Tie};
  837. return \%hash;
  838. }
  839. else {
  840. return {};
  841. }
  842. }
  843. #
  844. # Procedural interface
  845. #
  846. sub ParseConfig {
  847. #
  848. # @_ may contain everything which is allowed for new()
  849. #
  850. return (new Config::General(@_))->getall();
  851. }
  852. sub SaveConfig {
  853. #
  854. # 2 parameters are required, filename and hash ref
  855. #
  856. my ($file, $hash) = @_;
  857. if (!$file || !$hash) {
  858. croak "SaveConfig(): filename and hash argument required.";
  859. }
  860. else {
  861. if (ref($hash) ne "HASH") {
  862. croak "The second parameter must be a reference to a hash!";
  863. }
  864. else {
  865. (new Config::General(-ConfigHash => $hash))->save_file($file);
  866. }
  867. }
  868. }
  869. sub SaveConfigString {
  870. #
  871. # same as SaveConfig, but return the config,
  872. # instead of saving it
  873. #
  874. my ($hash) = @_;
  875. if (!$hash) {
  876. croak "SaveConfigString(): Hash argument required.";
  877. }
  878. else {
  879. if (ref($hash) ne "HASH") {
  880. croak "The parameter must be a reference to a hash!";
  881. }
  882. else {
  883. return (new Config::General(-ConfigHash => $hash))->save_string();
  884. }
  885. }
  886. }
  887. # keep this one
  888. 1;
  889. =head1 NAME
  890. Config::General - Generic Config Module
  891. =head1 SYNOPSIS
  892. #
  893. # the OOP way
  894. use Config::General;
  895. $conf = new Config::General("rcfile");
  896. my %config = $conf->getall;
  897. #
  898. # the procedural way
  899. use Config::General;
  900. my %config = ParseConfig("rcfile");
  901. =head1 DESCRIPTION
  902. This module opens a config file and parses it's contents for you. The B<new> method
  903. requires one parameter which needs to be a filename. The method B<getall> returns a hash
  904. which contains all options and it's associated values of your config file.
  905. The format of config files supported by B<Config::General> is inspired by the well known apache config
  906. format, in fact, this module is 100% compatible to apache configs, but you can also just use simple
  907. name/value pairs in your config files.
  908. In addition to the capabilities of an apache config file it supports some enhancements such as here-documents,
  909. C-style comments or multiline options.
  910. =head1 METHODS
  911. =over
  912. =item new()
  913. Possible ways to call B<new()>:
  914. $conf = new Config::General("rcfile");
  915. $conf = new Config::General(\%somehash);
  916. $conf = new Config::General( %options ); # see below for description of possible options
  917. This method returns a B<Config::General> object (a hash blessed into "Config::General" namespace.
  918. All further methods must be used from that returned object. see below.
  919. You can use the new style with hash parameters or the old style which is of course
  920. still supported. Possible parameters to B<new()> are:
  921. * a filename of a configfile, which will be opened and parsed by the parser
  922. or
  923. * a hash reference, which will be used as the config.
  924. An alternative way to call B<new()> is supplying an option- hash with one or more of
  925. the following keys set:
  926. =over
  927. =item B<-ConfigFile>
  928. A filename or a filehandle, i.e.:
  929. -ConfigFile => "rcfile" or -ConfigFile => \$FileHandle
  930. =item B<-ConfigHash>
  931. A hash reference, which will be used as the config, i.e.:
  932. -ConfigHash => \%somehash
  933. =item B<-String>
  934. A string which contains a whole config, or an arrayref
  935. containing the whole config line by line.
  936. The parser will parse the contents of the string instead
  937. of a file. i.e:
  938. -String => $complete_config
  939. it is also possible to feed an array reference to -String:
  940. -String => \@config_lines
  941. =item B<-AllowMultiOptions>
  942. If the value is "no", then multiple identical options are disallowed.
  943. The default is "yes".
  944. i.e.:
  945. -AllowMultiOptions => "no"
  946. see B<IDENTICAL OPTIONS> for details.
  947. =item B<-LowerCaseNames>
  948. If set to a true value, then all options found in the config will be converted
  949. to lowercase. This allows you to provide case-in-sensitive configs. The
  950. values of the options will B<not> lowercased.
  951. =item B<-UseApacheInclude>
  952. If set to a true value, the parser will consider "include ..." as valid include
  953. statement (just like the well known apache include statement).
  954. =item B<-IncludeRelative>
  955. If set to a true value, included files with a relative path (i.e. "cfg/blah.conf")
  956. will be opened from within the location of the configfile instead from within the
  957. location of the script($0). This works only if the configfile has a absolute pathname
  958. (i.e. "/etc/main.conf").
  959. If the variable B<-ConfigPath> has been set and if the file to be included could
  960. not be found in the location relative to the current config file, the module
  961. will search within B<-ConfigPath> for the file. See the description of B<-ConfigPath>
  962. for more details.
  963. =item B<-ConfigPath>
  964. As mentioned above, you can use this variable to specify a search path for relative
  965. config files which have to be included. Config::General will search within this
  966. path for the file if it cannot find the file at the location relative to the
  967. current config file.
  968. You must specify the path as an array ref. For example:
  969. @path = qw(/usr/lib/perl /nfs/apps/lib /home/lib);
  970. ..
  971. -ConfigPath => \@path
  972. =item B<-MergeDuplicateBlocks>
  973. If set to a true value, then duplicate blocks, that means blocks and named blocks,
  974. will be merged into a single one (see below for more details on this).
  975. The default behavior of Config::General is to create an array if some junk in a
  976. config appears more than once.
  977. =item B<-MergeDuplicateOptions>
  978. If set to a true value, then duplicate options will be merged. That means, if the
  979. same option occurs more than once, the last one will be used in the resulting
  980. config hash.
  981. Setting this option implies B<-AllowMultiOptions == false> unless you set
  982. B<-AllowMultiOptions> explicit to 'true'. In this case duplicate blocks are
  983. allowed and put into an array but dupclicate options will be merged.
  984. =item B<-AutoLaunder>
  985. If set to a true value, then all values in your config file will be laundered
  986. to allow them to be used under a -T taint flag. This could be regarded as circumventing
  987. the purpose of the -T flag, however, if the bad guys can mess with your config file,
  988. you have problems that -T will not be able to stop. AutoLaunder will only handle
  989. a config file being read from -ConfigFile.
  990. =item B<-AutoTrue>
  991. If set to a true value, then options in your config file, whose values are set to
  992. true or false values, will be normalised to 1 or 0 respectively.
  993. The following values will be considered as B<true>:
  994. yes, on, 1, true
  995. The following values will be considered as B<false>:
  996. no, off, 0, false
  997. This effect is case-insensitive, i.e. both "Yes" or "oN" will result in 1.
  998. =item B<-FlagBits>
  999. This option takes one required parameter, which must be a hash reference.
  1000. The supplied hash reference needs to define variables for which you
  1001. want to preset values. Each variable you have defined in this hash-ref
  1002. and which occurs in your config file, will cause this variable being
  1003. set to the preset values to which the value in the config file refers to.
  1004. Multiple flags can be used, separated by the pipe character |.
  1005. Well, an example will clarify things:
  1006. my $conf = new Config::General(
  1007. -ConfigFile => "rcfile",
  1008. -FlagBits => {
  1009. Mode => {
  1010. CLEAR => 1,
  1011. STRONG => 1,
  1012. UNSECURE => "32bit" }
  1013. }
  1014. );
  1015. In this example we are defining a variable named I<"Mode"> which
  1016. may contain one or more of "CLEAR", "STRONG" and "UNSECURE" as value.
  1017. The appropriate config entry may look like this:
  1018. # rcfile
  1019. Mode = CLEAR | UNSECURE
  1020. The parser will create a hash which will be the value of the key "Mode". This
  1021. hash will contain B<all> flags which you have pre-defined, but only those
  1022. which were set in the config will contain the pre-defined value, the other
  1023. ones will be undefined.
  1024. The resulting config structure would look like this after parsing:
  1025. %config = (
  1026. Mode => {
  1027. CLEAR => 1,
  1028. UNSECURE => "32bit",
  1029. STRONG => undef,
  1030. }
  1031. );
  1032. This method allows the user (or, the "maintainer" of the configfile for your
  1033. application) to set multiple pre-defined values for one option.
  1034. Please beware, that all occurencies of those variables will be handled this
  1035. way, there is no way to distinguish between variables in different scopes.
  1036. That means, if "Mode" would also occur inside a named block, it would
  1037. also parsed this way.
  1038. Values which are not defined in the hash-ref supplied to the parameter B<-FlagBits>
  1039. and used in the corresponding variable in the config will be ignored.
  1040. Example:
  1041. # rcfile
  1042. Mode = BLAH | CLEAR
  1043. would result in this hash structure:
  1044. %config = (
  1045. Mode => {
  1046. CLEAR => 1,
  1047. UNSECURE => undef,
  1048. STRONG => undef,
  1049. }
  1050. );
  1051. "BLAH" will be ignored silently.
  1052. =item B<-DefaultConfig>
  1053. This can be a hash reference or a simple scalar (string) of a config. This
  1054. causes the module to preset the resulting config hash with the given values,
  1055. which allows you to set default values for particular config options directly.
  1056. =item B<-Tie>
  1057. B<-Tie> takes the name of a Tie class as argument that each new hash should be
  1058. based off of.
  1059. This hash will be used as the 'backing hash' instead of a standard perl hash,
  1060. which allows you to affect the way, variable storing will be done. You could, for
  1061. example supply a tied hash, say Tie::DxHash, which preserves ordering of the
  1062. keys in the config (which a standard perl hash won't do). Or, you could supply
  1063. a hash tied to a DBM file to save the parsed variables to disk.
  1064. There are many more things to do in tie-land, see L<tie> to get some interesting
  1065. ideas.
  1066. If you want to use the B<-Tie> feature together with B<-DefaultConfig> make sure
  1067. that the hash supplied to B<-DefaultConfig> must be tied to the same Tie class.
  1068. Make sure that the hash which receives the generated hash structure (e.g. which
  1069. you are using in the assignment: %hash = $config->getall()) must be tied to
  1070. the same Tie class.
  1071. Example:
  1072. use Config::General;
  1073. use Tie::IxHash;
  1074. tie my %hash, "Tie::IxHash";
  1075. %hash = ParseConfig(
  1076. -ConfigFile => shift(),
  1077. -Tie => "Tie::IxHash"
  1078. );
  1079. =item B<-InterPolateVars>
  1080. If set to a true value, variable interpolation will be done on your config
  1081. input. See L<Config::General::Interpolated> for more informations.
  1082. =item B<-ExtendedAccess>
  1083. If set to a true value, you can use object oriented (extended) methods to
  1084. access the parsed config. See L<Config::General::Extended> for more informations.
  1085. =item B<-StrictObjects>
  1086. By default this is turned on, which causes Config::General to croak with an
  1087. error if you try to access a non-existent key using the oop-way (B<-ExtendedAcess>
  1088. enabled). If you turn B<-StrictObjects> off (by setting to 0 or "no") it will
  1089. just return an empty object/hash/scalar. This is valid for OOP-access 8via AUTOLOAD
  1090. and for the methods obj(), hash() and value().
  1091. =item B<-StrictVars>
  1092. By default this is turned on, which causes Config::General to croak with an
  1093. error if an undefined variable with B<InterPolateVars> turned on occurs
  1094. in a config. Set to I<false> (i.e. 0) to avoid such error messages.
  1095. =item B<-SplitPolicy>
  1096. You can influence the way how Config::General decides which part of a line
  1097. in a config file is the key and which one is the value. By default it tries
  1098. it's best to guess. That means you can mix equalsign assignments and whitespace
  1099. assignments.
  1100. However, somtimes you may wish to make it more strictly for some reason. In
  1101. this case you can set B<-SplitPolicy>. The possible values are: 'guess' which
  1102. is the default, 'whitespace' which causes the module to split by whitespace,
  1103. 'equalsign' which causes it to split strictly by equal sign, or 'custom'. In the
  1104. latter case you must also set B<-SplitDelimiter> to some regular expression
  1105. of your choice. For example:
  1106. -SplitDelimiter => '\s*:\s*'
  1107. will cause the module to split by colon while whitespaces which surrounds
  1108. the delimiter will be removed.
  1109. Please note that the delimiter used when saving a config (save_file() or save_string())
  1110. will be choosen accordingto the current B<-SplitPolicy>. If -SplitPolicy is
  1111. set to 'guess' or 'whitespace', 3 whitespaces will be used to delimit saved
  1112. options. If 'custom' is set, then you need to set B<-StoreDelimiter>.
  1113. =item B<-SplitDelimiter>
  1114. Set this to any arbitrary regular expression which will be used for option/value
  1115. splitting. B<-SplitPolicy> must be set to 'custom' to make this work.
  1116. =item B<-StoreDelimiter>
  1117. You can use this parameter to specify a custom delimiter to use when saving
  1118. configs to a file or string. You only need to set it if you want to store
  1119. the config back to disk and if you have B<-SplitPolicy> set to 'custom'.
  1120. Be very carefull with this parameter.
  1121. =item B<-CComments>
  1122. Config::General is able to notice c-style comments (see section COMMENTS).
  1123. But for some reason you might no need this. In this case you can turn
  1124. this feature off by setting B<-CComments> to a false value('no', 0, 'off').
  1125. By default B<-CComments> is turned on.
  1126. =back
  1127. =item getall()
  1128. Returns a hash structure which represents the whole config.
  1129. =item save_file()
  1130. Writes the config hash back to the harddisk. This method takes one or two
  1131. parameters. The first parameter must be the filename where the config
  1132. should be written to. The second parameter is optional, it must be a
  1133. reference to a hash structure, if you set it. If you do not supply this second parameter
  1134. then the internal config hash, which has already been parsed, will be
  1135. used.
  1136. Please note, that any occurence of comments will be ignored by getall()
  1137. and thus be lost after you call this method.
  1138. You need also to know that named blocks will be converted to nested blocks
  1139. (which is the same from the perl point of view). An example:
  1140. <user hans>
  1141. id 13
  1142. </user>
  1143. will become the following after saving:
  1144. <user>
  1145. <hans>
  1146. id 13
  1147. </hans>
  1148. </user>
  1149. Example:
  1150. $conf_obj->save_file("newrcfile", \%config);
  1151. or, if the config has already been parsed, or if it didn't change:
  1152. $conf_obj->save_file("newrcfile");
  1153. =item save_string()
  1154. This method is equivalent to the previous save_file(), but it does not
  1155. store the generated config to a file. Instead it returns it as a string,
  1156. which you can save yourself afterwards.
  1157. It takes one optional parameter, which must be a reference to a hash structure.
  1158. If you omit this parameter, the internal config hash, which has already been parsed,
  1159. will be used.
  1160. Example:
  1161. my $content = $conf_obj->save_string(\%config);
  1162. or:
  1163. my $content = $conf_obj->save_string();
  1164. =back
  1165. =head1 CONFIG FILE FORMAT
  1166. Lines begining with B<#> and empty lines will be ignored. (see section COMMENTS!)
  1167. Spaces at the begining and the end of a line will also be ignored as well as tabulators.
  1168. If you need spaces at the end or the beginning of a value you can use
  1169. apostrophs B<">.
  1170. An optionline starts with it's name followed by a value. An equalsign is optional.
  1171. Some possible examples:
  1172. user max
  1173. user = max
  1174. user max
  1175. If there are more than one statements with the same name, it will create an array
  1176. instead of a scalar. See the example below.
  1177. The method B<getall> returns a hash of all values.
  1178. =head1 BLOCKS
  1179. You can define a B<block> of options. A B<block> looks much like a block
  1180. in the wellknown apache config format. It starts with E<lt>B<blockname>E<gt> and ends
  1181. with E<lt>/B<blockname>E<gt>. An example:
  1182. <database>
  1183. host = muli
  1184. user = moare
  1185. dbname = modb
  1186. dbpass = D4r_9Iu
  1187. </database>
  1188. Blocks can also be nested. Here is a more complicated example:
  1189. user = hans
  1190. server = mc200
  1191. db = maxis
  1192. passwd = D3rf$
  1193. <jonas>
  1194. user = tom
  1195. db = unknown
  1196. host = mila
  1197. <tablestructure>
  1198. index int(100000)
  1199. name char(100)
  1200. prename char(100)
  1201. city char(100)
  1202. status int(10)
  1203. allowed moses
  1204. allowed ingram
  1205. allowed joice
  1206. </tablestructure>
  1207. </jonas>
  1208. The hash which the method B<getall> returns look like that:
  1209. print Data::Dumper(\%hash);
  1210. $VAR1 = {
  1211. 'passwd' => 'D3rf$',
  1212. 'jonas' => {
  1213. 'tablestructure' => {
  1214. 'prename' => 'char(100)',
  1215. 'index' => 'int(100000)',
  1216. 'city' => 'char(100)',
  1217. 'name' => 'char(100)',
  1218. 'status' => 'int(10)',
  1219. 'allowed' => [
  1220. 'moses',
  1221. 'ingram',
  1222. 'joice',
  1223. ]
  1224. },
  1225. 'host' => 'mila',
  1226. 'db' => 'unknown',
  1227. 'user' => 'tom'
  1228. },
  1229. 'db' => 'maxis',
  1230. 'server' => 'mc200',
  1231. 'user' => 'hans'
  1232. };
  1233. If you have turned on B<-LowerCaseNames> (see new()) then blocks as in the
  1234. following example:
  1235. <Dir>
  1236. <AttriBUTES>
  1237. Owner root
  1238. </attributes>
  1239. </dir>
  1240. would produce the following hash structure:
  1241. $VAR1 = {
  1242. 'dir' => {
  1243. 'attributes' => {
  1244. 'owner => "root",
  1245. }
  1246. }
  1247. };
  1248. As you can see, the keys inside the config hash are normalized.
  1249. Please note, that the above config block would result in a
  1250. valid hash structure, even if B<-LowerCaseNames> is not set!
  1251. This is because I<Config::General> does not
  1252. use the blocknames to check if a block ends, instead it uses an internal
  1253. state counter, which indicates a block end.
  1254. If the module cannot find an end-block statement, then this block will be ignored.
  1255. =head1 NAMED BLOCKS
  1256. If you need multiple blocks of the same name, then you have to name every block.
  1257. This works much like apache config. If the module finds a named block, it will
  1258. create a hashref with the left part of the named block as the key containing
  1259. one or more hashrefs with the right part of the block as key containing everything
  1260. inside the block(which may again be nested!). As examples says more than words:
  1261. # given the following sample
  1262. <Directory /usr/frisco>
  1263. Limit Deny
  1264. Options ExecCgi Index
  1265. </Directory>
  1266. <Directory /usr/frik>
  1267. Limit DenyAll
  1268. Options None
  1269. </Directory>
  1270. # you will get:
  1271. $VAR1 = {
  1272. 'Directory' => {
  1273. '/usr/frik' => {
  1274. 'Options' => 'None',
  1275. 'Limit' => 'DenyAll'
  1276. },
  1277. '/usr/frisco' => {
  1278. 'Options' => 'ExecCgi Index',
  1279. 'Limit' => 'Deny'
  1280. }
  1281. }
  1282. };
  1283. You cannot have more than one named block with the same name because it will
  1284. be stored in a hashref and therefore be overwritten if a block occurs once more.
  1285. =head1 IDENTICAL OPTIONS
  1286. You may have more than one line of the same option with different values.
  1287. Example:
  1288. log log1
  1289. log log2
  1290. log log2
  1291. You will get a scalar if the option occured only once or an array if it occured
  1292. more than once. If you expect multiple identical options, then you may need to
  1293. check if an option occured more than once:
  1294. $allowed = $hash{jonas}->{tablestructure}->{allowed};
  1295. if(ref($allowed) eq "ARRAY") {
  1296. @ALLOWED = @{$allowed};
  1297. else {
  1298. @ALLOWED = ($allowed);
  1299. }
  1300. The same applies to blocks and named blocks too (they are described in more detail
  1301. below). For example, if you have the following config:
  1302. <dir blah>
  1303. user max
  1304. </dir>
  1305. <dir blah>
  1306. user hannes
  1307. </dir>
  1308. then you would end up with a data structure like this:
  1309. $VAR1 = {
  1310. 'dir' => {
  1311. 'blah' => [
  1312. {
  1313. 'user' => 'max'
  1314. },
  1315. {
  1316. 'user' => 'hannes'
  1317. }
  1318. ]
  1319. }
  1320. };
  1321. As you can see, the two identical blocks are stored in a hash which contains
  1322. an array(-reference) of hashes.
  1323. Under some rare conditions you might not want this behavior with blocks (and
  1324. named blocks too). If you want to get one single hash with the contents of
  1325. both identical blocks, then you need to turn the B<new()> parameter B<-MergeDuplicateBlocks>
  1326. on (see above). The parsed structure of the example above would then look like
  1327. this:
  1328. $VAR1 = {
  1329. 'dir' => {
  1330. 'blah' => [
  1331. 'user' => 'max',
  1332. 'user' => 'hannes'
  1333. ]
  1334. }
  1335. };
  1336. As you can see, there is only one hash "dir->{blah}" containing multiple
  1337. "user" entries. As you can also see, turning on B<-MergeDuplicateBlocks>
  1338. does not affect scalar options (i.e. "option = value"). In fact you can
  1339. tune merging of duplicate blocks and options independent from each other.
  1340. If you don't want to allow more than one identical options, you may turn it off
  1341. by setting the flag I<AllowMultiOptions> in the B<new()> method to "no".
  1342. If turned off, Config::General will complain about multiple occuring options
  1343. with identical names!
  1344. =head1 LONG LINES
  1345. If you have a config value, which is too long and would take more than one line,
  1346. you can break it into multiple lines by using the backslash character at the end
  1347. of the line. The Config::General module will concatenate those lines to one single-value.
  1348. Example:
  1349. command = cat /var/log/secure/tripwire | \
  1350. mail C<-s> "report from tripwire" \
  1351. honey@myotherhost.nl
  1352. command will become:
  1353. "cat /var/log/secure/tripwire | mail C<-s> 'report from twire' honey@myotherhost.nl"
  1354. =head1 HERE DOCUMENTS
  1355. You can also define a config value as a so called "here-document". You must tell
  1356. the module an identifier which identicates the end of a here document. An
  1357. identifier must follow a "<<".
  1358. Example:
  1359. message <<EOF
  1360. we want to
  1361. remove the
  1362. homedir of
  1363. root.
  1364. EOF
  1365. Everything between the two "EOF" strings will be in the option I<message>.
  1366. There is a special feature which allows you to use indentation with here documents.
  1367. You can have any amount of whitespaces or tabulators in front of the end
  1368. identifier. If the module finds spaces or tabs then it will remove exactly those
  1369. amount of spaces from every line inside the here-document.
  1370. Example:
  1371. message <<EOF

Large files files are truncated, but you can click here to view the full file