How to limit the module area to a subroutine?

if I run the following script:

use strict; use warnings; sub load { use File::Path qw (make_path); } load(); make_path('1/2/3/4'); exit 0; 

It works great. I would like to limit the loaded module to a subroutine so that I cannot use subroutines declared in the module outside the subroutine that loads it. Is it possible?

+4
source share
2 answers

Short answer: No, this is really impossible.

The long answer: after loading File :: Path, you cannot prevent the code from calling File::Path::make_path() , but you can limit the area in which it is available to a short name.

 use File::Path (); sub load { local *make_path = \&File::Path::make_path; make_path('foo/bar/baz'); # This would work... } File::Path::make_path('bang/kapow'); # This would work too make_path('xyxxy/plugh'); # But this would die 

But, using local , the scope is not lexically limited by the syntax code block. This is a dynamically limited value, meaning that all code called load() will also see make_path as a working routine.

I would recommend not using this technique because it is unclear and it can be difficult to explain the side effects from a distance. Basically, I find this useful for writing unit tests where you could replace some features with layouts.

Perl developers are discussing the addition of lexical subnets as part of the language. This function should allow you to do almost what you want, with no problems using local . But this is still ongoing and not even available in perl development releases.

+11
source

In short: you cannot. Even “worse”, use compile time is executed, so it does not matter that you put it in your sub (except for cosmetic benefits).

+4
source

Source: https://habr.com/ru/post/1436615/


All Articles