Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

Re: Source filters in eval/require

by tilly (Archbishop)
on Oct 05, 2003 at 16:57 UTC ( #296728=note: print w/replies, xml ) Need Help??

in reply to Source filters in eval/require

I don't have the energy to work out all of the details of how to do it, but here is an approach that I know can work.

It is now possible to put anonymous subroutines in @INC. They get 2 arguments, the first being itself, the second being the module to load. It is supposed to return undef if it won't handle the request, and a filehandle otherwise. It can also look at caller to figure out who is asking. See perlfunc in 5.8 or better for details. (It was there earlier, but not documented IIRC.)

So put a subroutine there that examines caller, and if the caller is one that you think should get your filtering, find and read the file you are requiring, slap your filter on the start, and return a filehandle to that in-memory filter.

Trapping eval is also doable with this strategy. Replace eval with a call to a function that puts the code to eval in a given variable, and does a require that the sub above will decide to handle by slapping its stuff on the variable in question, and returning a filehandle to it. Your choice on how to get sub and require to cooperate.

I would lean towards only putting one closure in @INC when your module is loaded, and then make import (and unimport if you want) work by manipulating lexical data which your import subroutine will examine in making its decision about whether it should trap any given require. (This because your import will potentially get called a lot, adding to @INC each time is..overkill.)

I also think that it would be good if source-filters had some easy way to trap evals. But generally I would prefer that they not trap requires unless I ask for it because that makes it tricky and potentially dangerous to load existing code from within a filtered piece of code. (Furthermore the results cannot be guaranteed - what if the require'ed code was loaded before yours? Then it isn't filtered.) Therefore I might limit your hack to just evals and/or require's that you somehow know are intended to be yours.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://296728]
and a soft breeze sighs...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (3)
As of 2018-06-24 01:39 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (126 votes). Check out past polls.