Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Expanding environment variables from ini file

by pryrt (Monsignor)
on Aug 27, 2019 at 13:41 UTC ( #11105118=note: print w/replies, xml ) Need Help??


in reply to Expanding environment variables from ini file

Using Config::Tiny, and assuming you don't actually need it to be in %ENV, but you just want to treat them as internal "environment-style" variables, and also want to accept true environment variables

#!/usr/bin/perl -l # in reponse to https://perlmonks.org/?node_id=11105105 use warnings; use strict; use Config::Tiny; my $ini_string = do { local $/; <DATA> }; $ini_string =~ s/(?<=.);.*$//gmx; # Config::Tiny cannot handle p +ostfix comments my $cfg = Config::Tiny->read_string($ini_string); #use Data::Dumper; $Data::Dumper::Indent = 1; #print Dumper $cfg; # the _ key holds the main-category / top-level of your .ini file; # if you have multiple categories, this loop will have to be modifie +d foreach my $key (keys %{$cfg->{_}}) { while( $cfg->{_}{$key} =~ /\%(.*?)\%/g ) { my $var = $1; next unless exists $cfg->{_}{$var} or exists $ENV{$var}; #print "\$var = >>$var<<\n"; my $repl = exists $cfg->{_}{$var} ? $cfg->{_}{$var} : $ENV{$va +r}; $cfg->{_}{$key} =~ s/\%$var\%/$repl/; } } #print Dumper $cfg; print $cfg->write_string(); __DATA__ ;comments PROJECT_HOME=D:\Scripts\Projectname\ ;comments package1=pack_test package1_home=%PROJECT_HOME%%package1% subtemp=%TEMP%\subdir

On mine, that output

PROJECT_HOME=D:\Scripts\Projectname\ package1=pack_test package1_home=D:\Scripts\Projectname\pack_test subtemp=C:\Users\pryrt\AppData\Local\Temp\subdir

update: finished my first sentence; sorry

Replies are listed 'Best First'.
Re^2: Expanding environment variables from ini file
by Lotus1 (Vicar) on Aug 27, 2019 at 15:41 UTC
    >>Using Config::Tiny, and assuming you don't actually need it to be in %ENV, but you just want to treat them as internal "environment-style" variables, and also want to accept true environment variables

    Your assumptions are mostly correct. Eventually I don't really need to use %ENV, but while I'm still using a mix of batch and Perl scripts I plan to keep using it.

    I like this approach of using Config::Tiny to parse the ini and then do the substitutions in my code. I've had good luck with Config::Tiny before so I'm already familiar with it. I can let it handle validation and parsing.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11105118]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (3)
As of 2021-02-25 07:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?