Perl _ DATA _ use records and configuration reading

Source: Internet
Author: User

#! /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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.