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

前端 未结 4 1696
误落风尘
误落风尘 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: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();
    

提交回复
热议问题