rovf has asked for the wisdom of the Perl Monks concerning the following question:
Dear Monks:
This is once more a question to a problem which I have already solved in a different way, but where I would like to know why my first attempt failed.
Inspired by a suggestion I got for a different problem, I now wanted to solve the following task: Write a module Master.pm which, when called like this:
would cause a function nx defined inside the package of Slave. My first attempt went like this:package Slave; use Master;
Using the debugger, I indeed could see that this function would end up in the symbol table of package Slave; but when I defined do_something as:package Master; use strict; use warnings; sub import { my $target = caller; no strict 'refs'; *{"$target\::nx"} = sub { do_something() } }
I found that this prints Master, not Slave as the calling package. This puzzled me. Well, I ended up writing the defining line in the import function like this:package Slave; use strict; use warnings; use Master; sub do_something { my $pkg=caller(); print "$pkg\n"; }
and this works now as expected, but I still would like to know why my original attempt had failed.eval "package $caller; sub nx { do_something() }";
|
|---|