How can I get the name of the current subroutine in Perl?

前端 未结 4 1667
误落风尘
误落风尘 2020-12-29 03:14

In Perl we can get the name of the current package and current line number Using the predefined variables like __PACKAGE__ and __LINE__.

Li

相关标签:
4条回答
  • 2020-12-29 03:28

    Use the caller() function:

    my $sub_name = (caller(0))[3];

    This will give you the name of the current subroutine, including its package (e.g. 'main::test'). Closures return names like 'main::__ANON__'and in eval it will be '(eval)'.

    0 讨论(0)
  • 2020-12-29 03:36

    I was just looking for an answer to this question as well, I found caller as well, but I was not interested in the fully qualified path, simply the literal current package name of the sub, so I used:

    my $current_sub = (split(/::/,(caller(0))[3]))[-1];

    Seems to work perfectly, just adding it in for if anyone else trips over this questions :)

    0 讨论(0)
  • 2020-12-29 03:39

    There special __SUB__ exists from perl-5.16.

    use v5.16;
    use Sub::Identify qw/sub_fullname/;
    sub foo {
        print sub_fullname( __SUB__ );  # main::foo
    }
    
    foo();
    

    Actually you can pass to sub_fullname any subroutine reference (even anonymous):

    use Sub::Identify qw/sub_fullname/;
    sub foo {
        print sub_fullname( \&foo );  # main::foo
        print sub_fullname( sub{} );  # main::__ANON__
    }
    
    foo();
    
    0 讨论(0)
  • 2020-12-29 03:48

    caller is the right way to do at @eugene pointed out if you want to do this inside the subroutine.

    If you want another piece of your program to be able to identify the package and name information for a coderef, use Sub::Identify.

    Incidentally, looking at

    sub test()
    {
        print __LINE__;
    }
    &test();
    

    there are a few important points to mention: First, don't use prototypes unless you are trying to mimic builtins. Second, don't use & when invoking a subroutine unless you specifically need the effects it provides.

    Therefore, that snippet is better written as:

    sub test
    {
        print __LINE__;
    }
    test();
    
    0 讨论(0)
提交回复
热议问题