INI文件的解析

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

package IniConf;
use base 'Exporter';
use strict;
#export function
our @EXPORT    = qw(load_conf get_conf_value);
#hash table to hold conf file
my $map={};
sub load_conf {
    my $file = shift;
    open CONF,"$file" or return ;
    binmode CONF,":utf8";

    #if no section specified,put it into "global" section
    my $st="global";
    while(my $line=<CONF>) {
        chomp($line);
        #remove prefix and suffiex space
        $line =~ s/^\s+//;
        $line =~ s/\s+$//;
        next if $line eq "";
        my $first_c = substr($line,0,1);
        #skip comments 
        next if $first_c eq '#';

        if ( $first_c eq '[' && substr($line,-1) eq ']' ) {
            $st = substr($line,1,length($line)-2);
        } else {
            my ($k,$v) = ( $line =~ /([^=]+)=(.+)/ );
            $k =~ s/^\s+//;
            $k =~ s/\s+$//;

            $v =~ s/^\s+//;
            $v =~ s/\s+$//;

            $map->{$st}->{$k} = $v;
        }
    }
    close CONF;
}

sub get_conf_value
{
    my ($k,$sec)  = @_;
    $sec = "global" if not defined $sec;
    return "" unless ( exists $map->{$sec} && exists $map->{$sec}->{$k} ) ;
    return $map->{$sec}->{$k};
}
1;