简体   繁体   中英

How can I handle configuration files in Perl?

I'm refactoring an old script that does some operations on different sites. It needs to use a configuration file which is now a manually parsed text file with this format:

label:domain:username:password:path

Of course the number of lines is potentially unlimited.

I know there are a few modules which deal with config files. Which one is the best for this situation?

If you are looking to change the format, please look at the recommendations here:

How do you manage configuration files in Perl?

If you're looking to parse the existing format, that format looks to be more of a comma-separated file than a "configuration" file, so I'd say go with Text::CSV (it allows you to choose a separator character in a constructor, so you can do colon-separated instead of comma-separated), or for very large files Text::CSV_XS.

use Text::CSV; # Example adapted from POD

my @rows;
my $csv = Text::CSV->new ( { sep_char => ":" } )  
             or die "Cannot use CSV: ".Text::CSV->error_diag ();

open my $fh, "<:encoding(utf8)", "test.conf" or die "test.conf: $!";
while ( my $row = $csv->getline( $fh ) ) {
    push @rows, $row; # $row is arrayref containing your fields
}
$csv->eof or $csv->error_diag();
close $fh;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM