APM: One liner to get hash from an environment list

David Slimp rock808 at davidslimp.com
Thu Jan 22 11:39:03 CST 2004


As I tested this out some more, I found a serious problem
in the original RegEx when using quotes... I also
have a fix.... might wanna use this test program:

The 2nd RegEx in the while loop is the problem one.

=============================== CUT ========================
#!/usr/bin/perl -w

while (<DATA>) {
        /^\s*([^#].*?)\s*=\s*(['"]?)(.*)\2/ and $config{$1}=$3;
        #/^\s*([^#].*?)\s*=\s*['"]?(.*)['"]?/ and $config{$1}=$2;
}

foreach $k (keys %config) {
        print ":$k:$config{$k}:\n";
}

__DATA__

a=b
this = that
     hi =       bye
#commeent = not allows

text=he said, "hi!" to me.
quote=don't do that!
key="some value"


=============================== CUT ========================



On Thu, Jan 22, 2004 at 10:45:41AM -0600, Sam Foster wrote:
> >%config = map { /(.*?)=['"]?(.*)['"]?/ } qx(cat 
> >/etc/defaults/some_prog_env.sh);
> >
> >This should parse any valid bourne shell syntax key=value config file
> >into a hash.
> 
> but if you want to allow #comments, blank lines etc, you might end up 
> with something like this?
> 
> my %config;
> foreach ( qx(cat /your/input/file) ) {
> 	next if /^\s*#/;	# skip commented lines
> 
> 	# match for name=value pairs, allowing for indentation and
> 	# options whitespace around the '='.
> 	# We should really use a backreference to pair up the quotes?
> 	next unless ( /\s*(.*?)\s*=\s*['"]?(.*)['"]?/ );
> 	$config{$1} = $2;
> }
> 
> Can you combine the regexps to get this back on one line? (for those 
> who take joy from this sort of thing?)
> 
> Sam
> 
> _______________________________________________
> Austin mailing list
> Austin at mail.pm.org
> http://mail.pm.org/mailman/listinfo/austin

-- 
David Slimp
rock808 at DavidSlimp.com             Do you use Linux?!
http://www.DavidSlimp.com          Get Counted!  http://counter.li.org/
Jabber IM:  rock808 at jabber.org     fax: 801-858-4102
"He who desires the fruit, waters the tree."  --  Nguyen Trai 



More information about the Austin mailing list