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

I'm not sure if this is possible, but if it is, it would be quite helpful to me.

I'd like to know if there is a way to detect the name of a perl program which has imported a given perl module within that module, so that the information on module usage can be logged to a file.

Basically, I'd like to reverse-engineer which modules are being used by which programs in production; one way would be to drop in a module which logs the name of it's calling program every time it is used. After a period of time (several weeks/months) the typical usage pattern could be detected.

The other option I can think of involves something conceptually along the lines of:

for module in <list of modules to investigate>;do grep $module `find / | xargs file | grep Perl | cut -d":" -f1` done
which will probably be slow no matter how I code it.

Suggestions?

Replies are listed 'Best First'.
Re: Auto-detecting module usage
by diotalevi (Canon) on Jan 24, 2006 at 00:01 UTC

    Examine caller() from inside your module's &import.

    ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊

      Thanks. Together with tirwhan's suggestion, that's exactly what I needed. :-)
Re: Auto-detecting module usage
by tirwhan (Abbot) on Jan 24, 2006 at 09:11 UTC

    Nobody's mentioned $0 yet, so I will, because that actually does what you're asking for in your question (i.e. give you the name of the script which is running when your module is loaded). However, judging from the purpose you describe, you'll be better off with diotalevi's suggestion, to use caller() to determine what has loaded your module, because that will return the file your module was loaded from. For example if you have, in Flim.pm

    package Flim; sub new { print "Caller: ".join("-",caller())."\n"; print '$0: '.$0."\n"; }
    in Flam.pm:
    package Flam; use Flim; sub new { Flim->new(); }
    and in flimflam.pl:
    use Flam; Flam->new();
    This will print out
    Caller: Flam-/Flam.pm-3 $0: flimflam.pl

    There are ten types of people: those that understand binary and those that don't.
      Thanks, I had completely forgotten about $0. That's exactly what I wanted. :-)
Re: Auto-detecting module usage
by socketdave (Curate) on Jan 23, 2006 at 22:51 UTC
      Devel::Dependencies solves the *opposite* problem; given a program or module, it tells me which modules depend on that program.

      I want the reverse: if I'm a module, what program just loaded me? I don't want to know what modules a given program depends on; I want to know whether a given module on my system is actually *used* by any program on the system, and if so, which one.

        So, all you have to do is go through all the scripts, and construct the list of modules they use. Fill a database table with that info, and then you can scan the reverse relations.
        Sorry... I misread your question. Are you preparing to migrate these scripts to a new system?