Esteemed Monks...

What is the best way for config file to contain perl code, for example stub routines, right now I'm usually slurping config file via required

#... require "/etc/myname.cfg"; ..

I tried config file modules but they're usually not flexible enough, and require way more code and awareness then simple require... and such simple method work great for specifying values, arrays, hashes etc... but what about subs?

Back to the point, I would like to specify something as a callback, or generally would like to allow defining perl code in config... my current solution looks like that:

# /etc/myscript.cfg $somehash = { 'Somestuff'=> { #... }, 'Someotherstuff'=> { #.... 'Actions'=> [ "print \"hello world\";", ] }, }
And then I just eval lines from Actions array.

This looks awkward in configfile, because of all this quoting required, and editors won't hilight this correctly, I'm having problems accessing variables from such eval'd code, etc,

to sum this up - code specified in configfile looks extremely ugly and unclear.

Are there better ways to do that?

UPDATE: Based on feedback I updated my method to something like this:

package Scriptname; require "/etc/scriptname.cfg"
package Scriptname; $somehash=> { 'Something'=> { #.. stuff .. 'Sub' => sub { print "Hello world, "; print "here is my local var: $var\n"; }; } };
This one is a little easier on the eyes, instead of eval I use
my $sub=$somehash->{'Something'}->{'Sub'}; &$sub() if defined($sub);

Still not perfect, but it's a serious improvement over the mess I used to create... thanks.


In reply to What's the best way to put perl code in config file? by Eyck

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.