天天看點

讀取自定義配置檔案

配置檔案樣例

# more test.conf 

### Database Configration ####

host = 10.8.9.20;

dbname = webdb ;

user = admin ;

pwd = admin;

2.測試程式内容

#!/usr/bin/perl

use strict;

our($host, $dbname, $user, $password);

my $prog_root="/usr/test_prog";

my $prog_conf = $prog_root."/test.conf";

open my $conf_file,"<",$prog_conf;

my @conf_items = <$conf_file>;

close($conf_file);

foreach my $line(@conf_items){

   #### read each line from configration file

   $host = $1 if ($line =~/host\s*=\s*(\S+)\s*;/i);

   $dbname=$1 if ($line =~/dbname\s*=\s*(\S+)\s*;/i);

   $user=$1 if ($line =~/user\s*=\s*(\S+)\s*;/i);

   $password=$1 if ($line =~/pwd\s*=\s*(\S+)\s*;/i);

}

print "$host\n";

print "$dbname\n";

print "$user\n";

print "$password\n";

3.運作輸出結果

# perl conf.pl 

10.8.9.20

webdb

admin

本文轉自 pgmia 51CTO部落格,原文連結:http://blog.51cto.com/heyiyi/1596282