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