Friday, April 10, 2020

Save and Load config file in Perl

sub loadConfigFile {
    if ( ( defined $_[0] ) && ( open my $fh, "<$_[0]" ) ) {
        local $/ = undef; #set Input record separator for reading file in one shot, set $/ to empty str '' doesn't work
        my $str = <$fh>;
        close $fh;
        $/ = "\n";
        my ($meta_build_ref,$cfgref,$pathsref);
        eval $str;

        #%cfg=%$cfgref; CanNOT do this way, it will create a new %cfg
        if ( $log_level >= $LLV_DBG ) { print "meta_build=$meta_build\n";}
        #foreach my $key ( keys %cfg ) { $cfg{$key} = $$cfgref{$key}; } =>this will change the array ref
        foreach my $key ( keys %cfg ) {
            for my $i (0..$#{$cfg{$key}})
            {
                $cfg{$key}[$i] = $$cfgref{$key}[$i];
            }
        }
        if ( $log_level >= $LLV_DBG ) { print Data::Dumper->Dump( [ \%cfg ] ); }
        foreach my $key ( keys %paths ) {
            if(defined $$pathsref{$key}) {$paths{$key}=$$pathsref{$key};}
            else {$paths{$key}=undef;}
        }
        if ( $log_level >= $LLV_DBG ) { print Data::Dumper->Dump( [ \%paths ] ); }
    }
}

sub loadConfig {
    my $filename = $mw->getOpenFile(
        -defaultextension => '.cfg',
        -filetypes  => [ [ 'Config Files', ['.cfg'] ], [ 'All Files', '*', ], ],
        -initialdir => $home_dir, #'./'
    );
    loadConfigFile($filename);
    $info="Loaded $filename";
}

sub saveConfig {
    my $filename = $mw->getSaveFile(
        -defaultextension => '.cfg',
        -filetypes  => [ [ 'Config Files', ['.cfg'] ], [ 'All Files', '*', ], ],
        -initialdir => $home_dir, #'./'
    );
    if ( ( defined $filename ) && ( open my $fh, ">$filename" ) ) {
        print $fh "\$asic='$asic';\n";
        print $fh "\$meta_build='$meta_build';\n";
        my $str = Data::Dumper->Dump( [ \%cfg ], ['$cfgref'] );
        print $fh $str;
        if ( $log_level > $LLV_DBG ) { print $str; }
        $str = Data::Dumper->Dump( [ \%paths ], ['$pathsref'] );
        print $fh $str;
        if ( $log_level > $LLV_DBG ) { print $str; }
        close $fh;
    }
}

0 Comments:

Post a Comment