#! /Usr/bin/perl
# File: Data. pl
# Author: Darkstar
# Date: 2014/08/26
Use strict;
Use warnings;
Use diagnostics;
Use Data: dumper;
My % config;
While (<DATA>)
{
Next if/^ \ s *#/;
Next unless/\ s * (\ W +) \ s * = \ s * (\ W +) \ s */;
My ($ key, $ value) = ($1, $2 );
If (exists $ config {$ key }){
If (! Ref $ config {$ key }){
$ Config {$ key} = [$ config {$ key}];
}
Push @ {$ config {$ key}, $ value;
}
Else {
$ Config {$ key} = $ value;
}
}
Print dumper (% config );
_ DATA __
# Comment
# Line
Database = MySQL
Username = hwy
Pass =
Hostname = localhost
Use = A1
Use = a2
Use = A3
Data is read only once. If you want to read data multiple times in a script
Seek data, 0, 0;
----------------------- Add
Seek data, 0, 0;
While (<DATA> ){
Chomp;
Print;
}
You can see the effect. If you comment on seek data, 0, 0, you can compare the differences.
Generally, we put the configuration in a separate file and can use a dedicated module to read the explanation. For example, the default app config generated by the dacner is read because the file format is yaml, use the config: yaml module to solve the problem.
#! /Usr/bin/perl
#
Use 5.10.0;
Use strict;
Use warnings;
Use Data: dumper;
# Use config: Tiny; # Read. ini config
Use config: yaml;
My $ c = config: yaml-> New (Config => "/home/hwy/MyApp/config. yml ",
Output => "/tmp/CC. cfg ",
);
Say $ C-> {appname}; # traditional read configuration method
Say $ C-> {charset };
$ C-> {charset} = 'gb2312'; # reset the encoding of the configuration file.
Say $ C-> get_appname; # OOP attribute reading Method
Say $ C-> get_charset;
$ C-> write;
View/tmp/CC. cfg to view the newly generated configuration file.
Perl _ DATA _ use records and configuration reading