ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП |
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы. |
11.8. Creating References to MethodsProblemYou want to store a reference to a method. SolutionCreate a closure that makes the proper method call on the appropriate object. DiscussionWhen you ask for a reference to a method, you're asking for more than just a raw function pointer. You also need to record which object the method needs to be called upon as the object contains the data the method will work with. The best way to do this is using a closure. Assuming $mref = sub { $obj->meth(@_) }; # later... $mref->("args", "go", "here"); Even when Be aware that the notation: $sref = \$obj->meth; doesn't do what you probably expected. It first calls the method on that object and gives you either a reference to the return value or a reference to the last of the return values if the method returns a list. The $cref = $obj->can("meth"); This produces a code ref to the appropriate method (should one be found), one that carries no object information. Think of it as a raw function pointer. The information about the object is lost. That's why you need a closure to capture both the object state as well as the method to call. See AlsoThe discussion on methods in the Introduction to Chapter 13; Recipe 11.7; Recipe 13.7 |