In Perl, how can I check from which module a given function was imported?

后端 未结 4 1192
既然无缘
既然无缘 2020-12-03 05:25

I have a code which calls the function. But I don\'t know the module this function belongs to. I need it to modify this function.

How can I check it?

4条回答
  •  离开以前
    2020-12-03 05:42

    Perl's debugger can dig down the way you want. For example:

    main::(-e:1):  0
      DB<1> sub foo {}
    
      DB<2> x \&foo
    0  CODE(0xca6898)
       -> &main::foo in (eval 5)[/usr/share/perl/5.10/perl5db.pl:638]:2-2

    It does this using Devel::Peek:

    =head2 C I
    
    Calls L to try to find the glob the ref lives in; returns
    C if L can't be loaded, or if C can't
    find a glob for this ref.
    
    Returns C<< I::I >> if the code ref is found in a glob.
    
    =cut
    
    sub CvGV_name_or_bust {
        my $in = shift;
        return unless ref $in;
        $in = \&$in;            # Hard reference...
        eval { require Devel::Peek; 1 } or return;
        my $gv = Devel::Peek::CvGV($in) or return;
        *$gv{PACKAGE} . '::' . *$gv{NAME};
    } ## end sub CvGV_name_or_bust
    

    You might exercise it with

    #! /usr/bin/perl
    
    use warnings;
    use strict;
    
    package Foo;
    
    sub bar {}
    
    package main;
    
    BEGIN { *baz = \&Foo::bar }
    
    sub CvGV_name_or_bust { ... }
    
    print CvGV_name_or_bust(\&baz), "\n";
    

    Output:

    Foo::bar

    Note that the example above gives Foo:bar a different name, but you get both the package where the aliased sub resides and also its name there.

提交回复
热议问题