in reply to Can you limit the scope of require?

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!"