language/perl

[Perl] Config 파일 읽어들이기

alignG 2009. 10. 8. 22:40
완전 심플한 버전의 설정파일 읽어들이기 입니다.
cpan에는 이런 저런 것들이 있는데 그렇게 강한 기능들은 사용할 일이 없어서 이런식으로 사용하는게 편한것 같습니다.

config.txt
namsa=wow
nan1004au=cool


Mconfig.pm
package Config;
#constructor
sub new{
    my $class = shift;;
    my $self = {
        _path => shift,
        _config => shift,
    };
    bless $self,$class;
    init($self);
    return $self;
}

#설정파일로부터 읽어 들이기
sub init{
    my ($self)  = @_;
    open my $config, '<',$self->{_path} or die $!;
    while(<$config>){
        chomp;
        (my $key, my @value) = split /=/,$_;
        ${$self->{_config}}{$key} = join '=' , @value;
    }
}
 
sub get_pram{
    my ($self,$paramater) = @_;
    return ${$self->{_config}}{$paramater};  
}

sub print{
    my ($self) = @_;
    while(my ($key,$value) = each(%{$self->{_config}})){
        print "$key is $value \n";
    }
}

sub set_pram{
    my ($self,$paramater,$value) = @_;
    ${$self->{_config}}{$paramater} = $value;
    open(CONFIG,">",$self->{_path}) or die $!;
    while(my ($key,$value) = each(%{$self->{_config}})){
        print CONFIG "$key" . "=" . "$value" . "\n";
    }
    init($self);
}
1;



run.pl
use MConfig;

my $m = MConfig->new("config.txt");
$m->print();
print "====================\n";
$m->set_pram("abc","bc");
$m->print();





반응형