How can lazily load a Perl variable?

I have a variable that I need to pass to the subroutine. It is very possible that the routine will not need this variable, and the value of the variable will be expensive. Is it possible to create a lazy load object that will only be evaluated if it is actually used? I can't change the routine myself, so it should still look like a normal Perl scalar to the caller.

+4
source share
4 answers

You need to look at Data :: Lazy and Scalar :: Defer . Update: There are also Data :: Thunk and Scalar :: Lazy .

I have not tried any of them myself, but I am not sure that they work correctly for the object. To do this, you can try the Moose class, which stores the real object in lazy , which handles provides all the methods that the object provides. (This will not work if the routine performs isa checking, although if it does not call isa as a method, in which case you can override it in your class.)

+6
source

Data::Thunk is the most transparent and reliable way to do this that I know of.

However, I am not a big fan of this or any other similar modules or methods that try to hide themselves from the user. I prefer something more explicit, for example, having code that uses a value that is difficult to compute, just calls a function to retrieve it. This way, you don’t need to pre-comprehend your value, your intentions are more clearly visible, and you can also have various options to avoid recalculating the value, for example, lexical closures, perl state variables, or Memoize modules.

+5
source

You can see the binding .

+2
source

I would suggest stepping back and rethinking how you structure your program. Instead of passing the variable to a method that may not be needed, make this value available in some other way, for example, by calling another method, which can be called if necessary (and not when it is not).

In Moose, such data is ideally stored in attributes. You can make the attributes lazily constructed, so they are not calculated until they are needed, but after that the value is saved, so it does not need to be calculated a second time.

+1
source

All Articles