in reply to Just before subroutine returns

You've got excellent answers, but I think it's important to explain that they fall into different categories.

The one category shown is basically installing a wrapper with the same name, and execute code before the original sub is entered and after it is exited. This is very stable and easy to achieve without changing the monitored sub, but comes with the drawback that information about internal state- i.e. lexical vars - is lost.

The other category shown is adding a lexical inside the sub, which holds an object. At the moment the sub (or generally the scope) is left , lexicals without reference count will be destructed and the DESTROY method will be called. This method can trigger a call back which can display the internal state in its closure.

But I'm not sure that you can know achieve info where - i.e. at which return - the sub is left.

A third - yet not demonstrated - category is to use the debugger. There you can define watch and trace expressions for subs which will trigger at different points. But this approach comes with dramatically reduced execution speed and won't be appropriate inside a long running process, like e.g. a web application.

So the appropriate answer depends on the exact nature of the information you (or someone else digging up this thread) wants to gather. :)

HTH

Cheers Rolf
(addicted to the Perl Programming Language and ☆☆☆☆ :)
Je suis Charlie!

  • Comment on Re: Just before subroutine returns (depends)

Replies are listed 'Best First'.
Re^2: Just before subroutine returns (depends)
by Anonymous Monk on Aug 29, 2017 at 16:11 UTC
    The fourth category is those of us who are just glad we don't have to read the OP's code. This one sub has so many returns that he can't just put a log statement in front of each of them? Yikes!

      Log statement for each of many returns or log statement for each of many execution branches comes to the same number of log statements if you are trying to determine execution sequence as is implied by OP's question. So there is no "logging" advantage to multiple returns here, and there are vast opportunities to make the flow of code clearer by using early exits.

      Multiply nested conditional code blocks and loops with a single exit: Yikes! (throws up hands and runs away).

      Premature optimization is the root of all job security
      We - or at least me - don't answer for the OP but for the archive.

      There are many possible cases where one needs to monitor subs, like e.g. needing to maintain foreign code and needing to figure out the intended mechanics.

      And PM is not Stack-Overflow, our strength is to have deep discussions not just singular case recipes.

      Cheers Rolf
      (addicted to the Perl Programming Language and ☆☆☆☆ :)
      Je suis Charlie!

      Maybe the OP didn't write the code, just inherited it.