Determining the subroutine name of a Perl code reference

后端 未结 4 1275
隐瞒了意图╮
隐瞒了意图╮ 2020-12-29 05:14

How would one determine the subroutine name of a Perl code reference? I would also like to distinguish between named and anonymous subroutines.

Thanks to this quest

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-29 06:10

    I'm not sure about calling the name of the function from the outside, but you can get it from within the subroutine via the caller function:

    sub Foo {print "foo!\n";return (caller(0))[3];}
    $function_name=Foo();
    print "Called $function_name\n";
    

    This has the following output:

    foo!
    Called main::Foo
    

    Of course, you can return the function name as one of the items that the subroutine returns. That way, you can capture it and have the option of displaying it (or using it in other logic, etc).

提交回复
热议问题