http://qs1969.pair.com?node_id=11141003


in reply to Re: How to identify the package of a subroutine given only a reference to it
in thread How to identify the package of a subroutine given only a reference to it

Hi,

Yes, it is a subroutine I generate through an eval, in a custom package

I was toying with the idea that I could track the package with only the ref to the generated subroutine. However, I need to do package housekeeping when the sub is no longer required.

So now have an object which contains the package name and the generated subroutine. The package name obtained using the __PACKAGE__ like you mentioned.

Thanks for the welcome!

  • Comment on Re^2: How to identify the package of a subroutine given only a reference to it

Replies are listed 'Best First'.
Re^3: How to identify the package of a subroutine given only a reference to it
by choroba (Cardinal) on Feb 01, 2022 at 00:11 UTC
    But beware!

    #!/usr/bin/perl use warnings; use strict; { package Local; sub My::frob { print __PACKAGE__ } } My::frob(); # Local

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
Re^3: How to identify the package of a subroutine given only a reference to it
by LanX (Saint) on Feb 01, 2022 at 02:32 UTC
    > So now have an object which contains the package name and the generated subroutine

    If you want to go that way you can also choose to bless the code ref directly.

    Objects don't need to be hashes in Perl.

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery

      I'm partial to array backed objects where applicable. But I've never actually tried a blessed code ref... until 5 minutes ago after reading your reply! It might be a good solution to my application.

      Out of interest, do you have insight on how perl knows to call the underlying code ref and not a method that may or may not be in the package? An extra lookup/check must be done when called?

      #eg $code_ref_obj->();#calls code ref directly $code_ref_obj->a_method(); #Call a method on the object
      Thanks again for you comments
        > do you have insight on how perl knows to call the underlying code ref

        I'm not sure I understand, your demo nailed it.

        • $code_ref->(ARGS) without method name is de-referencing the code-ref.
        • $obj->method_name(ARGS) with method name is looking up the "blessed" package inside the structure of the scalar and will try to resolve the method there.

        Cheers Rolf
        (addicted to the Perl Programming Language :)
        Wikisyntax for the Monastery