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

jeffsto has asked for the wisdom of the Perl Monks concerning the following question:

I've started putting my code into modules for obvious reasons. Is there a way I can get the name of the script that is calling the module? I want to use this for tracking so I can easily keep track of what scripts call my modules. I've looked at the module "caller" however I couldn't determine if it could extract the correct information. It seemed like it was limited to the information within the module itself, or did I miss something? Thanks!

Replies are listed 'Best First'.
Re: Module caller
by choroba (Cardinal) on May 06, 2015 at 13:36 UTC
    Yes, caller should do what you want.

    MyModule.pm:

    package MyModule; use warnings; use strict; print __PACKAGE__, ' called from ', (caller)[1], ".\n"; sub func { return 2 * shift } __PACKAGE__

    script.pl:

    #!/usr/bin/perl use warnings; use strict; use MyModule; warn MyModule::func(21);

    Output:

    MyModule called from ./script.pl. 42 at ./script.pl line 8.
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

      Make sure you read the documetation on how callerworks -- knowing how many layers back to go, and what is actually supported on your platform (notably if Windows), might take some playing with it to see what you get.

      print __PACKAGE__, ' called from ', (caller)1, ".\n"; Worked perfect! Its exactly what I was looking for. Thanks!
Re: Module caller
by suaveant (Parson) on May 06, 2015 at 13:41 UTC
    FindBin or $0 could also be used.

                    - Ant
                    - Some of my best work - (1 2 3)

      I should think Findbinand $0 would be more helpful in figuring out how the script was called, but I don't see how it can help find who called the Module.

      Can you post an example?

        You said the name of the script calling the module, so I'd assumed you meant the actual script being run. If you mean what file the use or require was called from then no, FindBin and $0 won't help in that case.

                        - Ant
                        - Some of my best work - (1 2 3)

Re: Module caller
by LanX (Saint) on May 09, 2015 at 18:31 UTC
    >  Is there a way I can get the name of the script that is calling the module?

    The demonstrated technique will show you were the first use was.

    If you wanna know all places which do a use', put the check for caller into you 'import() sub.

    Maybe just using Carp might be easier.

    Cheers Rolf
    (addicted to the Perl Programming Language and ☆☆☆☆ :)
    Je suis Charlie!