I'd just turn the Perl data structure into something else. Not seeing the actual file, there might be some extra work that my solution doesn't do.
If the only thing that's in the file is the one variable declaration (so, no 1;
at the end, and so on), it can be really simple to turn your %config
it into YAML:
perl -MYAML -le 'print YAML::Dump( { do shift } )' filename
The do
returns the last thing it evaluated, so in this little code it returns the list of hash key-value pairs. Things such as YAML::Dump like to work with references so they get a hint about the top-level structure, so I make that into a hash reference by surrounding the do
with the curly braces. For your example, I'd get this YAML output:
---
(?-xism:^spam): eggs
color: red
numbers:
- 5
- 8
I don't know how Python will like that stringified regex, though. Do you really have a key that is a regex? I'd be curious to know how that's being used as part of the configuration.
If there's extra stuff in the file, life is a bit more tough. There's probably a really clever way to get around that, but I used the same idea, but just hard-coded the variable name that I wanted.
I tried this on the Perl data structure that the CPAN.pm module uses, and it looks like it came out fine. The only ugliness is the fore-knowledge of the variable name that it supplies. Now that you've seen the error of configuration in Perl code, avoid making the same mistake with Python code. :)
YAML:
perl -MYAML -le 'do shift; print YAML::Dump( $CPAN::Config )' MyConfig.pm
JSON:
perl -MJSON::Any -le 'do shift; my $j = JSON::Any->new; print $j->objToJson( $CPAN::Config )' MyConfig.pm
or
# suggested by JF Sebastian
perl -MJSON -le 'do shift; print to_json( $CPAN::Config )' MyConfig.pm
XML::Simple doesn't work out so well because it treated everything like an attribute, but maybe someone can improve on this:
perl -MXML::Simple -le 'do shift; print XMLout( $CPAN::Config )' MyConfig.pm