I am assuming that you can't modify the .conf files? If you can, then IMO the best solution (better than the following) would be to have them return or set references to anonymous subs rather than use named subs.

Otherwise, tybalt89 and dave_the_m have provided two possible solutions that I think are good. Since TIMTOWTDI, here's one more - this one stores references to the sub get_config in lexical variables, which has the advantage that they are normal variables with the same scoping rules, you can pass them around, etc.

I'm using do (with the recommended error handling) instead of require because the latter normally won't load a file more than once (see require and %INC). That means that if you were to use my load_config more than once on the same file, with require there is a chance that you could get a reference to the wrong sub, or it just plain wouldn't work. do executes the file every time, which avoids this.

Foo.conf:

use warnings; use strict; sub get_config { return "Foo!" } 1;

Bar.conf:

use warnings; use strict; sub get_config { return "Bar!" } 1;

main.pl:

use warnings; use strict; sub load_config { my $file = shift; local *get_config; if (not my $return = do $file) { die "couldn't parse $file: $@" if $@; die "couldn't do $file: $!" unless defined $return; die "couldn't run $file" unless $return; } return \&get_config; } my $foo = load_config( "Foo.conf" ); my $bar = load_config( "Bar.conf" ); print $foo->(), "\n"; # prints "Foo!" print $bar->(), "\n"; # prints "Bar!"

In reply to Re: Can you limit the scope of require? by haukex
in thread Can you limit the scope of require? by taylorK

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.