1package Config::Std; 2 3our $VERSION = '0.900'; 4 5require v5.7.3; # RT#21184 6 7my %global_def_sep; 8my %global_inter_gap; 9 10sub import { 11 my ($package, $opt_ref) = @_; 12 my $caller = caller(); 13 $global_def_sep{$caller} = $opt_ref->{def_sep}; 14 $global_inter_gap{$caller} = $opt_ref->{def_gap}; 15 for my $sub_name (qw( read_config write_config )) { 16 $opt_ref->{$sub_name} ||= $sub_name; 17 } 18 *{$caller.'::'.$opt_ref->{read_config}} = \&Config::Std::Hash::read_config; 19 *{$caller.'::'.$opt_ref->{write_config}} = \&Config::Std::Hash::write_config; 20} 21 22package Config::Std::Gap; 23use Class::Std; 24{ 25 sub serialize { return "\n" } 26 sub update {} 27 sub extend {} 28 sub copy_to {} 29} 30 31package Config::Std::Comment; 32use Class::Std; 33{ 34 my %text_of : ATTR( :init_arg<text> ); 35 36 sub serialize { 37 my ($self) = @_; 38 return $text_of{ident $self}; 39 } 40 41 sub append_comment { 42 my ($self, $new_text) = @_; 43 $text_of{ident $self} .= $new_text; 44 } 45 46 sub update {} 47 sub extend {} 48 sub copy_to {} 49} 50 51package Config::Std::Keyval; 52use Class::Std; 53{ 54 my %key_of : ATTR( :init_arg<key> :get<key> ); 55 my %vals_of : ATTR; 56 my %deleted_of : ATTR; 57 58 sub BUILD { 59 my ($self, $ident, $arg_ref) = @_; 60 61 $vals_of{$ident} = [ { %{$arg_ref} } ]; 62 } 63 64 my %SEPARATOR = ( ':' => ': ', '=' => ' = ' ); 65 66 use Carp; 67 68 sub serialize { 69 my ($self, $def_sep, $block_name) = @_; 70 my $ident = ident $self; 71 72 return "" if $deleted_of{$ident}; 73 74 my ($key, $vals) = ($key_of{$ident}, $vals_of{$ident}); 75 76 my $keyspace = q{ } x length($key); 77 78 my $serialization = q{}; 79 80 for $n (0..$#{$vals}) { 81 my ($val,$sep,$comm) = @{$vals->[$n]}{qw(val sep comm)}; 82 83 my $val_type = ref $val; 84 croak qq{Can't save \L$val_type\E ref as value for key {'$block_name'}{'$key'} (only scalars or array refs)} 85 if $val_type && $val_type ne 'ARRAY'; 86 87 $sep = $SEPARATOR{$sep || $def_sep}; 88 89 my @vals = $val_type eq 'ARRAY' ? @{$val} : $val; 90 s/ (?!\Z) \n /\n$keyspace$sep/gxms for @vals; 91 92 $serialization .= $comm || q{}; 93 94 $serialization .= join q{}, map {"$key$sep$_\n"} @vals; 95 } 96 97 return $serialization; 98 } 99 100 sub update { 101 my ($self, $hash_ref, $updated_ref) = @_; 102 my $ident = ident $self; 103 104 my $key = $key_of{$ident}; 105 106 if (!exists $hash_ref->{$key}) { 107 $deleted_of{$ident} = 1; 108 } 109 else { 110 my $val = $hash_ref->{$key}; 111 @newvals = ref $val eq 'ARRAY' ? @{$val} : $val; 112 for my $n (0..$#newvals) { 113 $vals_of{$ident}[$n]{val} = $newvals[$n]; 114 } 115 splice @{$vals_of{$ident}}, scalar @newvals; 116 } 117 118 $updated_ref->{$key} = 1; 119 120 return 1; 121 } 122 123 sub copy_to { 124 my ($self, $hash_ref) = @_; 125 my $ident = ident $self; 126 my @vals = map $_->{val}, @{$vals_of{$ident}}; 127 $hash_ref->{$key_of{$ident}} = @vals > 1 ? \@vals : $vals[0]; 128 } 129 130 sub multivalue { 131 my ($self, $sep, $val, $comm) = @_; 132 push @{$vals_of{ident $self}}, {val=>$val, sep=>$sep, comm=>$comm}; 133 } 134} 135 136package Config::Std::Block; 137use Class::Std; 138{ 139 my %name_of : ATTR( :init_arg<name> :get<name> default => '' ); 140 my %sep_count_of : ATTR; 141 my %precomm_of : ATTR( :init_arg<precomm> default => '' ); 142 my %parcomm_of : ATTR( :init_arg<parcomm> default => '' ); 143 my %components_of : ATTR; 144 my %deleted_of : ATTR; 145 my %seen : ATTR; 146 my %is_first : ATTR( :init_arg<first> default => '' ); 147 148 sub BUILD { 149 my ($self, $ident) = @_; 150 @{$sep_count_of{$ident}}{':','='} = (0,0); 151 $components_of{$ident} = []; 152 $seen{$ident} = {}; 153 } 154 155 sub copy_to { 156 my ($self, $hash_ref) = @_; 157 my $ident = ident $self; 158 159 my $keyvals = $hash_ref->{$name_of{$ident}} ||= {}; 160 161 for my $comp ( @{$components_of{$ident}} ) { 162 $comp->copy_to($keyvals); 163 } 164 165 $hash_ref->{$name_of{$ident}} = $keyvals; 166 } 167 168 sub serialize { 169 my ($self, $first, $caller, $post_gap, $inter_gap) = @_; 170 my $ident = ident $self; 171 172 return q{} if $deleted_of{$ident}; 173 174 my $is_anon = $first && length($name_of{$ident}) == 0; 175 176 my $serialization = q{}; 177 if (!$is_anon) { 178 $serialization = ($precomm_of{$ident} || q{}) 179 . "[$name_of{$ident}]" 180 . (defined $parcomm_of{$ident}?$parcomm_of{$ident}:q{}) 181 . "\n"; 182 } 183 184 my $gds = $global_def_sep{$caller}; 185 my $def_sep 186 = defined $gds ? $gds 187 : $sep_count_of{$ident}{':'} >= $sep_count_of{$ident}{'='} ? ':' 188 : '=' 189 ; 190 191 $self->ensure_gap() if $inter_gap && !$is_anon; 192 193 for my $comp ( @{$components_of{$ident}} ) { 194 $serialization .= $comp->serialize($def_sep, $name_of{$ident}); 195 } 196 197 return $serialization; 198 } 199 200 sub update { 201 my ($self, $hash_ref, $updated_ref) = @_; 202 my $ident = ident $self; 203 204 if (!defined $hash_ref) { 205 $deleted_of{$ident} = 1; 206 return; 207 } 208 209 for my $comp ( @{$components_of{$ident}} ) { 210 $comp->update($hash_ref, $updated_ref) or next; 211 } 212 } 213 214 sub extend { 215 my ($self, $hash_ref, $updated_ref, $post_gap, $inter_gap) = @_; 216 217 # Only the first occurrence of a block has new keys added... 218 return unless $is_first{ident $self}; 219 220 my $first = 1; 221 for my $key ( grep {!$updated_ref->{$_}} keys %{$hash_ref}) { 222 my $value = $hash_ref->{$key}; 223 my $separate = ref $value || $value =~ m/\n./xms; 224 $self->ensure_gap() if ($first ? $post_gap : $inter_gap) 225 || $separate; 226 $self->add_keyval($key, undef, $hash_ref->{$key}); 227 $self->add_gap() if $separate; 228 $first = 0; 229 } 230 } 231 232 sub ensure_gap { 233 my ($self) = @_; 234 my $comp_ref = $components_of{ident $self}; 235 return if @{$comp_ref} && $comp_ref->[-1]->isa('Config::Std::Gap'); 236 push @{$comp_ref}, Config::Std::Gap->new(); 237 } 238 239 sub add_gap { 240 my ($self) = @_; 241 push @{$components_of{ident $self}}, Config::Std::Gap->new(); 242 } 243 244 sub add_comment { 245 my ($self, $text) = @_; 246 my $comp_ref = $components_of{ident $self}; 247 if ($comp_ref && @{$comp_ref} && $comp_ref->[-1]->isa('Config::Std::Comment') ) { 248 $comp_ref->[-1]->append_comment($text); 249 } 250 else { 251 push @{$comp_ref}, Config::Std::Comment->new({text=>$text}); 252 } 253 } 254 255 sub add_keyval { 256 my ($self, $key, $sep, $val, $comm) = @_; 257 my $ident = ident $self; 258 259 $sep_count_of{$ident}{$sep}++ if $sep; 260 261 my $seen = $seen{$ident}; 262 263 if ($seen->{$key}) { 264 $seen->{$key}->multivalue($sep, $val, $comm); 265 return; 266 } 267 268 my $keyval 269 = Config::Std::Keyval->new({key=>$key, sep=>$sep, val=>$val, comm=>$comm}); 270 push @{$components_of{$ident}}, $keyval; 271 $seen->{$key} = $keyval; 272 } 273} 274 275package Config::Std::Hash; 276use Class::Std; 277{ 278 279 use Carp; 280 use Fcntl ':flock'; # import LOCK_* constants 281 282 my %post_section_gap_for :ATTR; 283 my %array_rep_for :ATTR; 284 my %filename_for :ATTR; 285 286 sub write_config (\[%$];$) { 287 my ($hash_ref, $filename) = @_; 288 $hash_ref = ${$hash_ref} if ref $hash_ref eq 'REF'; 289 290 $filename = $filename_for{$hash_ref} if @_<2; 291 292 croak "Missing filename for call to write_config()" 293 unless $filename; 294 295 my $caller = caller; 296 297 my $inter_gap 298 = exists $global_inter_gap{$caller} ? $global_inter_gap{$caller} 299 : 1; 300 my $post_gap 301 = $post_section_gap_for{$hash_ref} 302 || (defined $global_inter_gap{$caller} ? $global_inter_gap{$caller} 303 : 1 304 ); 305 306 # Update existing keyvals in each block... 307 my %updated; 308 for my $block ( @{$array_rep_for{$hash_ref}} ) { 309 my $block_name = $block->get_name(); 310 $block->update($hash_ref->{$block_name}, $updated{$block_name}||={}); 311 } 312 313 # Add new keyvals to the first section of block... 314 for my $block ( @{$array_rep_for{$hash_ref}} ) { 315 my $block_name = $block->get_name(); 316 $block->extend($hash_ref->{$block_name}, $updated{$block_name}, 317 $post_gap, inter_gap 318 ); 319 } 320 321 # Add new blocks at the end... 322 for my $block_name ( sort grep {!$updated{$_}} keys %{$hash_ref} ) { 323 my $block = Config::Std::Block->new({name=>$block_name}); 324 my $subhash = $hash_ref->{$block_name}; 325 my $first = 1; 326 for my $key ( keys %{$subhash} ) { 327 if (!defined $subhash->{$key}) { 328 croak "Can't save undefined value for key {'$block_name'}{'$key'} (only scalars or array refs)"; 329 } 330 my $value = $subhash->{$key}; 331 my $separate = ref $value || $value =~ m/\n./xms; 332 $block->ensure_gap() if ($first ? $post_gap : $inter_gap) 333 || $separate; 334 $block->add_keyval($key, undef, $value); 335 $block->add_gap() if $separate; 336 $first = 0; 337 } 338 $block->ensure_gap(); 339 push @{$array_rep_for{$hash_ref}}, $block; 340 } 341 342 open my $fh, '>', $filename 343 or croak "Can't open config file '$filename' for writing (\L$!\E)"; 344 345 flock($fh,LOCK_EX|LOCK_NB) 346 || croak "Can't write to locked config file '$filename'" 347 if ! ref $filename; 348 349 my $first = 1; 350 for my $block ( @{$array_rep_for{$hash_ref}} ) { 351 print {$fh} $block->serialize($first, scalar caller, $post_gap); 352 $first = 0; 353 } 354 355 flock($fh,LOCK_UN) if ! ref $filename; 356 357 return 1; 358 } 359 360 sub read_config ($\[%$]) { 361 my ($filename, $var_ref, $opt_ref) = @_; 362 my $var_type = ref($var_ref) || q{}; 363 my $hash_ref; 364 if ($var_type eq 'SCALAR' && !defined ${$var_ref} ) { 365 ${$var_ref} = $hash_ref = {}; 366 } 367 elsif ($var_type eq 'HASH') { 368 $hash_ref = $var_ref; 369 } 370 else { 371 croak q{Scalar second argument to 'read_config' must be empty}; 372 } 373 374 bless $hash_ref, 'Config::Std::Hash'; 375 376 my $blocks = $array_rep_for{$hash_ref} 377 = _load_config_for($filename, $hash_ref); 378 379 for my $block ( @{$blocks} ) { 380 $block->copy_to($hash_ref); 381 } 382 383 $filename_for{$hash_ref} = $filename; 384 385 # Remove initial empty section if no data... 386 if (!keys %{ $hash_ref->{q{}} }) { 387 delete $hash_ref->{q{}}; 388 } 389 390 return 1; 391 } 392 393 sub _load_config_for { 394 my ($filename, $hash_ref) = @_; 395 396 open my $fh, '<', $filename 397 or croak "Can't open config file '$filename' (\L$!\E)"; 398 flock($fh,LOCK_SH|LOCK_NB) 399 || croak "Can't read from locked config file '$filename'" 400 if !ref $filename; 401 my $text = do{local $/; <$fh>}; 402 flock($fh,LOCK_UN) if !ref $filename; 403 404 my @config_file = Config::Std::Block->new({ name=>q{}, first=>1 }); 405 my $comment = q{}; 406 my %seen; 407 408 # Start tracking whether section markers have gaps after them... 409 $post_section_gap_for{$hash_ref} = 0; 410 411 for ($text) { 412 pos = 0; 413 while (pos() < length() ) { 414 # Gap... 415 if (m/\G (?: [^\S\n]* (?:\n|\z)+)/gcxms) { 416 ### Found gap 417 $config_file[-1]->add_comment($comment) if $comment; 418 $config_file[-1]->add_gap(); 419 $comment = q{}; 420 } 421 422 # Comment... 423 elsif (m/\G (\s* [#;] [^\n]* (?:\n|\z) )/gcxms) { 424 ### Found comment: $1 425 $comment .= $1; 426 } 427 428 # Block... 429 elsif (m/\G ([^\S\n]*) [[] ( [^]\n]* ) []] ( ([^\S\n]*) [#;] [^\n]* )? [^\S\n]* (?:\n|\z)/gcxms) { 430 my ($pre, $name, $parcomm, $ws) = ($1, $2, $3, $4); 431 ### Found block: $name 432 if ($parcomm) { 433 $pre = 2 + length($pre) + length($name) + length($ws); 434 if (m/\G ( (?: \n? [ ]{$pre,} [#] [^\n]* )+ )/gcxms) { 435 $parcomm .= "\n$1"; 436 } 437 } 438 push @config_file, 439 Config::Std::Block->new({ 440 name => $name, 441 precomm => $comment, 442 parcomm => $parcomm, 443 first => !$seen{$name}++, 444 }); 445 $comment = q{}; 446 447 # Check for trailing gap... 448 $post_section_gap_for{$hash_ref} 449 += m/\G (?= [^\S\n]* (?:\n|\z) )/xms ? +1 : -1; 450 } 451 452 # Key/value... 453 elsif (m/\G [^\S\n]* ([^=:\n]+?) [^\S\n]* ([:=] [^\S\n]*) ([^\n]*) (?:\n|\z)/gcxms) { 454 my ($key, $sep, $val) = ($1, $2, $3); 455 456 my $pure_sep = $sep; 457 $pure_sep =~ s/\s*//g; 458 459 # Continuation lines... 460 my $continued = 0; 461 while (m/\G [^\S\n]* \Q$sep\E ([^\n]*) (?:\n|\z) /gcxms 462 || m/\G [^\S\n]* \Q$pure_sep\E ([^\n]*) (?:\n|\z) /gcxms 463 ) { 464 $val .= "\n$1"; 465 $continued = 1; 466 } 467 468 $val =~ s/\A \s*|\s* \z//gxms if !$continued; 469 470 ### Found kv: $key, $val 471 472 $config_file[-1]->add_keyval($key, $pure_sep, $val, 473 $comment); $comment = q{}; } 474 475 # Mystery... 476 else { 477 my ($problem) = m/\G ([^\n]{10,40}|.{10}) /gcxms; 478 die "Error in config file '$filename' near:\n\n\t$problem\n"; 479 } 480 } 481 } 482 483 return \@config_file; 484 } 485 486} 487 488 4891; # Magic true value required at end of module 490__END__ 491 492=head1 NAME 493 494Config::Std - Load and save configuration files in a standard format 495 496 497=head1 VERSION 498 499This document describes Config::Std version 0.900 500 501 502=head1 SYNOPSIS 503 504 use Config::Std; 505 506 # Load named config file into specified hash... 507 read_config 'demo2.cfg' => my %config; 508 509 # Extract the value of a key/value pair from a specified section... 510 $config_value = $config{Section_label}{key}; 511 512 # Change (or create) the value of a key/value pair... 513 $config{Other_section_label}{other_key} = $new_val; 514 515 # Update the config file from which this hash was loaded... 516 write_config %config; 517 518 # Write the config information to another file as well... 519 write_config %config, $other_file_name; 520 521 522=head1 DESCRIPTION 523 524This module implements yet another damn configuration-file system. 525 526The configuration language is deliberately simple and limited, and the 527module works hard to preserve as much information (section order, 528comments, etc.) as possible when a configuration file is updated. 529 530The whole point of Config::Std is to encourage use of one standard layout 531and syntax in config files. Damian says "I could have gotten away with it, I would have 532only allowed one separator. But it proved impossible to choose between C<:> and C<=> 533(half the people I asked wanted one, half wanted the other)." 534Providing round-trip file re-write is the spoonful of sugar to help the medicine go down. 535The supported syntax is within the general INI file family 536 537See Chapter 19 of "Perl Best Practices" (O'Reilly, 2005) 538for more detail on the 539rationale for this approach. 540 541=head2 Configuration language 542 543The configuration language is a slight extension of the Windows INI format. 544 545=head3 Comments 546 547A comment starts with a C<#> character (Perl-style) or a C<;> character 548(INI-style), and runs to the end of the same line: 549 550 # This is a comment 551 552 ; Ywis, eke hight thilke 553 554Comments can be placed almost anywhere in a configuration file, except inside 555a section label, or in the key or value of a configuration variable: 556 557 # Valid comment 558 [ # Not a comment, just a weird section label ] 559 560 ; Valid comment 561 key: value ; Not a comment, just part of the value 562 563NOTE BENE -- that last is a BAD EXAMPLE of what is NOT supported. 564This module supports full-line comments only, not on same line with semantic content. 565 566=head3 Sections 567 568A configuration file consists of one or more I<sections>, each of which is 569introduced by a label in square brackets: 570 571 [SECTION1] # Almost anything is a valid section label 572 573 [SECTION 2] # Internal whitespace is allowed (except newlines) 574 575 [%^$%^&!!!] # The label doesn't have to be alphanumeric 576 577 [ETC. ETC. AS MANY AS YOU WANT] 578 579The only restriction on section labels is that they must be by 580themselves on a single line (except for any surrounding whitespace or 581trailing comments), and they cannot contain the character C<]>. 582 583Every line after a given section label until the next section label (or 584the end of the config file) belongs to the given section label. If no 585section label is currently in effect, the current section has an empty 586label. In other words, there is an implicit: 587 588 [] # Label is the empty string 589 590at the start of each config file. 591 592=head3 Configuration variables 593 594Each non-empty line within a section must consist of the specification of a 595I<configuration variable>. Each such variable consists of a key and a string 596value. For example: 597 598 name: George 599 age: 47 600 601 his weight! : 185 602 603The key consists of every character (including internal whitespace) from 604the start of the line until the key/value separator. So, the previous 605example declares three keys: C<'name'>, C<'age'>, and C<'his weight!'>. 606 607Note that whitespace before and after the key is removed. This makes it easier 608to format keys cleanly: 609 610 name : George 611 age : 47 612 his weight! : 185 613 614The key/value separator can be either a colon (as above) or an equals sign, 615like so: 616 617 name= George 618 age= 47 619 his weight! = 185 620 621Both types of separators can be used in the same file, but neither can 622be used as part of a key. Newlines are not allowed in keys either. 623 624When writing out a config file, Config::Std tries to preserve whichever 625separator was used in the original data (if that data was read 626in). New data 627(created by code not parsed by C<read_config>) 628is written back with a colon as its default separator, 629unless you specify the only other separator value C<'='> when the module is loaded: 630 631 use Config::Std { def_sep => '=' }; 632 633Note that this does not change read-in parsing, 634does not change punctuation for values that were parsed, 635and will not allow values other than C<'='> or C<':'>. 636 637Everything from the first non-whitespace character after the separator, 638up to the end of the line, is treated as the value for the config variable. 639So all of the above examples define the same three values: C<'George'>, 640C<'47'>, and C<'185'>. 641 642In other words, any whitespace immediately surrounding the separator 643character is part of the separator, not part of the key or value. 644 645Note that you can't put a comment on the same line as a configuration 646variable. The C<# etc.> is simply considered part of the value: 647 648 [Delimiters] 649 650 block delims: { } 651 string delims: " " 652 comment delims: # \n 653 654You can comment a config var on the preceding or succeeding line: 655 656 [Delimiters] 657 658 # Use braces to delimit blocks... 659 block delims: { } 660 661 # Use double quotes to delimit strings 662 663 string delims: " " 664 665 # Use octothorpe/newline to delimit comments 666 comment delims: # \n 667 668 669=head3 Multi-line configuration values 670 671A single value can be continued over two or more lines. If the line 672immediately after a configuration variable starts with the separator 673character used in the variable's definition, then the value of the 674variable continues on that line. For example: 675 676 address: 742 Evergreen Terrace 677 : Springfield 678 : USA 679 680The newlines then form part of the value, so the value specified in the 681previous example is: C<S<"742 Evergreen Terrace\nSpringfield\nUSA">> 682 683Note that the second and subsequent lines of a continued value are considered 684to start where the whitespace after the I<original> separator finished, not 685where the whitespace after their own separator finishes. For example, if the 686previous example had been: 687 688 address: 742 Evergreen Terrace 689 : Springfield 690 : USA 691 692then the value would be: 693 694 "742 Evergreen Terrace\n Springfield\n USA" 695 696If a continuation line has less leading whitespace that the first line: 697 698 address: 742 Evergreen Terrace 699 : Springfield 700 : USA 701 702it's treated as having no leading whitespace: 703 704 "742 Evergreen Terrace\nSpringfield\nUSA" 705 706 707=head3 Multi-part configuration values 708 709If the particular key appears more than once in the same section, it is 710considered to be part of the same configuration variable. The value of 711that configuration value is then a list, containing all the individual 712values for each instance of the key. For example, given the definition: 713 714 cast: Homer 715 cast: Marge 716 cast: Lisa 717 cast: Bart 718 cast: Maggie 719 720the corresponding value of the C<'cast'> configuration variable is: 721C<S<['Homer', 'Marge', 'Lisa', 'Bart', 'Maggie']>> 722 723Individual values in a multi-part list can also be multi-line (see 724above). For example, given: 725 726 extras: Moe 727 : (the bartender) 728 729 extras: Smithers 730 : (the dogsbody) 731 732the value for the C<'extras'> config variable is: 733C<S<["Moe\n(the bartender)", "Smithers\n(the dogsbody)"]>> 734 735 736=head2 Internal representation 737 738Each section label in a configuration file becomes a top-level hash key whe 739the configuration file is read in. The corresponding value is a nested hash 740reference. 741 742Each configuration variable's key becomes a key in that nested hash reference. 743Each configuration variable's value becomes the corresponding value in that nested hash reference. 744 745Single-line and multi-line values become strings. Multi-part values become 746references to arrays of strings. 747 748For example, the following configuration file: 749 750 # A simple key (just an identifier)... 751 simple : simple value 752 753 # A more complex key (with whitespace)... 754 more complex key : more complex value 755 756 # A new section... 757 [MULTI-WHATEVERS] 758 759 # A value spread over several lines... 760 multi-line : this is line 1 761 : this is line 2 762 : this is line 3 763 764 # Several values for the same key... 765 multi-value: this is value 1 766 multi-value: this is value 2 767 multi-value: this is value 3 768 769would be read into a hash whose internal structure looked like this: 770 771 { 772 # Default section... 773 '' => { 774 'simple' => 'simple value', 775 'more complex key' => 'more complex value', 776 }, 777 778 # Named section... 779 'MULTI-WHATEVERS' => { 780 'multi-line' => "this is line 1\nthis is line 2\nthis is line 3", 781 782 'multi-value' => [ 'this is value 1', 783 'this is value 2', 784 'this is value 3' 785 ], 786 } 787 } 788 789 790=head1 INTERFACE 791 792The following subroutines are exported automatically whenever the module is 793loaded... 794 795=over 796 797=item C<< read_config($filename => %config_hash) >> 798 799=item C<< read_config($filename => $config_hash_ref) >> 800 801=item C<< read_config($string_ref => %config_hash_or_ref) >> 802 803The C<read_config()> subroutine takes two arguments: the filename of a 804configuration file, and a variable into which the contents of that 805configuration file are to be loaded. 806 807If the variable is a hash, then the configuration sections and their 808key/value pairs are loaded into nested subhashes of the hash. 809 810If the variable is a scalar with an undefined value, a reference to an 811anonymous hash is first assigned to that scalar, and that hash is then 812filled as described above. 813 814The subroutine returns true on success, and throws an exception on failure. 815 816If you pass a reference to the string as the first argument to 817C<read_config()> it uses that string as the source of the config info. 818For example: 819 820 use Config::Std; 821 822 # here we load the config text to a scalar 823 my $cfg = q{ 824 [Section 1] 825 attr1 = at 826 attr2 = bat 827 828 [Section 2] 829 attr3 = cat 830 }; 831 832 # here we parse the config from that scalar by passing a reference to it. 833 read_config( \$cfg, my %config ); 834 835 use Data::Dumper 'Dumper'; 836 warn Dumper [ \%config ]; 837 838 839=item C<< write_config(%config_hash => $filename) >> 840 841=item C<< write_config($config_hash_ref => $filename) >> 842 843=item C<write_config(%config_hash)> 844 845=item C<write_config($config_hash_ref)> 846 847The C<write_config()> subroutine takes two arguments: the hash or hash 848reference containing the configuration data to be written out to disk, 849and an optional filename specifying which file it is to be written to. 850 851The data hash must conform to the two-level structure described earlier: 852with top-level keys naming sections and their values being references to 853second-level hashes that store the keys and values of the configuartion 854variables. If the structure of the hash differs from this, an exception is 855thrown. 856 857If a filename is also specified, the subroutine opens that file 858and writes to it. It no filename is specified, the subroutine uses the 859name of the file from which the hash was originally loaded using 860C<read_config()>. It no filename is specified and the hash I<wasn't> 861originally loaded using C<read_config()>, an exception is thrown. 862 863The subroutine returns true on success and throws and exception on failure. 864 865=back 866 867If necessary (typically to avoid conflicts with other modules), you can 868have the module export its two subroutines with different names by 869loading it with the appropriate options: 870 871 use Config::Std { read_config => 'get_ini', write_config => 'update_ini' }; 872 873 # and later... 874 875 get_ini($filename => %config_hash); 876 877 # and later still... 878 879 update_ini(%config_hash); 880 881You can also control how much spacing the module puts between single- 882line values when they are first written to a file, by using the 883C<def_gap> option: 884 885 # No empty line between single-line config values... 886 use Config::Std { def_gap => 0 }; 887 888 # An empty line between all single-line config values... 889 use Config::Std { def_gap => 1 }; 890 891Regardless of the value passed for C<def_gap>, new multi-line values are 892always written with an empty line above and below them. Likewise, values 893that were previously read in from a file are always written back with 894whatever spacing they originally had. 895 896=head1 DIAGNOSTICS 897 898=over 899 900=item Can't open config file '%s' (%s) 901 902You tried to read in a configuration file, but the file you specified 903didn't exist. Perhaps the filepath you specified was wrong. Or maybe 904your application didn't have permission to access the file you specified. 905 906=item Can't read from locked config file '$filename' 907 908You tried to read in a configuration file, but the file you specified 909was being written by someone else (they had a file lock active on it). 910Either try again later, or work out who else is using the file. 911 912=item Scalar second argument to 'read_config' must be empty 913 914You passed a scalar variable as the destination into C<read_config()> 915was supposed to load a configuration file, but that variable already had 916a defined value, so C<read_config()> couldn't autovivify a new hash for 917you. Did you mean to pass the subroutine a hash instead of a scalar? 918 919=item Can't save %s value for key '%s' (only scalars or array refs) 920 921You called C<write_config> and passed it a hash containing a 922configuration variable whose value wasn't a single string, or a list of 923strings. The configuration file format supported by this module only 924supports those two data types as values. If you really need to store 925other kinds of data in a configuration file, you should consider using 926C<Data::Dumper> or C<YAML> instead. 927 928=item Missing filename in call to write_config() 929 930You tried to calll C<write_config()> with only a configuration hash, but that 931hash wasn't originally loaded using C<read_config()>, so C<write_config()> has 932no idea where to write it to. Either make sure the hash you're trying to save 933was originally loaded using C<read_config()>, or else provide an explicit 934filename as the second argument to C<write_config()>. 935 936=item Can't open config file '%s' for writing (%s) 937 938You tried to update or create a configuration file, but the file you 939specified could not be opened for writing (for the reason given in the 940parentheses). This is often caused by incorrect filepaths or lack of 941write permissions on a directory. 942 943=item Can't write to locked config file '%s' 944 945You tried to update or create a configuration file, but the file you 946specified was being written at the time by someone else (they had a file 947lock active on it). Either try again later, or work out who else is 948using the file. 949 950=back 951 952 953=head1 CONFIGURATION AND ENVIRONMENT 954 955Config::Std requires no configuration files or environment variables. 956(To do so would be disturbingly recursive.) 957 958 959=head1 DEPENDENCIES 960 961This module requires the Class::Std module (available from the CPAN) 962 963 964=head1 INCOMPATIBILITIES 965 966Those variants of INI file dialect supporting partial-line comment are incompatible. 967(This is the price of keeping comments when re-writing.) 968 969 970=head1 BUGS AND LIMITATIONS 971 972=over 973 974=item Loading on demand 975 976If you attempt to load C<read_config()> and C<write_config()> 977at runtime with C<require>, you can not rely upon the prototype 978to convert a regular hash to a reference. To work around this, 979you must explicitly pass a reference to the config hash. 980 981 require Config::Std; 982 Config::Std->import; 983 984 my %config; 985 read_config($file, \%config); 986 write_config(\%config, $file); 987 988=item Windows line endings on Unix/Linux (RT#21547/23550) 989 990If the config file being read contains carriage returns and line feeds 991at the end of each line rather than just line feeds (i.e. the standard 992Windows file format, when read on a machine expecting POSIX file format), 993Config::Std emits an error with embedded newline. 994 995Workaround is match file line-endings to locale. 996 997This will be fixed in 1.000. 998 999 1000=item leading comment vanishes (RT#24597,) 1001 1002A comment before the first section is not always retained on write-back, if the '' default section is empty. 1003 1004=item 00write.t test 5 fails on perl5.8.1 (RT#17425) 1005 1006Due to an incompatible change in v5.8.1 partially reversed in v5.8.2, hash key randomisation can cause test to fail in that one version of Perl. Workaround is export environment variable PERL_HASH_SEED=0. 1007 1008=back 1009 1010Please report any bugs or feature requests to 1011C<bug-config-std@rt.cpan.org>, or through the web interface at 1012L<http://rt.cpan.org>. 1013 1014 1015=head1 AUTHOR 1016 1017Damian Conway C<< <DCONWAY@cpan.org> >> 1018Maintainers 1019Bill Ricker C<< <BRICKER@cpan.org> >> 1020Tom Metro C<< <tmetro@cpan.org> >> 1021 1022=head1 LICENCE AND COPYRIGHT 1023 1024Copyright (c) 2005, Damian Conway C<< <DCONWAY@cpan.org> >>. 1025Copyright (c) 2011, D.Conway, W.Ricker C<< <BRICKER@cpan.org> >> All rights reserved. 1026 1027This module is free software; you can redistribute it and/or 1028modify it under the same terms as Perl itself. 1029 1030 1031=head1 DISCLAIMER OF WARRANTY 1032 1033BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 1034FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 1035OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 1036PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER 1037EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 1038WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE 1039ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH 1040YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL 1041NECESSARY SERVICING, REPAIR, OR CORRECTION. 1042 1043IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 1044WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 1045REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE 1046LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, 1047OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE 1048THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 1049RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 1050FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 1051SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 1052SUCH DAMAGES. 1053