On 10/29/2014 02:47 PM, Morse, Richard E.,MGH wrote:
Hi! I'm running into an odd desire, and I'm hoping someone here can at least
tell me where to look, as so far Google and DDG are not telling me what I want.
I have a bunch of modules which have the same subroutines in each. Mostly, the
code for the subroutines is the same, but there is a chance that any particular
subroutine might be slightly different in any module (the context here involves
internationalization). So, for instance:
package PKG::en_US;
our %map;
sub handle_ages { ; }
sub handle_dests { ; }
package PKG::fr;
our %map;
sub handle_ages { ; }
sub handle_dests { ; }
package PKG::pt_BR;
our %map;
sub handle_ages { ; }
sub handle_dests { ; }
What I want to do is be able to create a base module, something like
package PKG::_base;
sub handle_ages { ; }
sub handle_dests { ; }
I could then define the rest of them as
package PKG::en_US;
our %map;
package PKG::fr;
our %map;
sub handle_dests { ; }
package PKG::pt_BR;
our %map;
Then use some kind of symbol table mungery to add the undefined functions to
each package.
This I can do.
However, where I need help, is that I want to be able to have the package variable
"%map" be properly used by the functions added to each package. That is, if I
call PKG::en_US::handle_ages, it should use %PKG::en_US::map, not (the nonexistant)
%PKG::_base::map.
I've tried various things, but from what I can understand, even with everything declared
"our", the sub definition closes over the package that it's in when defined. I've seen
references to doing an `eval ("package $package; sub handle_ages { ; }")`, but this makes
maintaining everything much harder, as I now don't have a base module, but rather a bunch of text
strings.
hi ricky,
i am somewhat confused as to your goal. you want each sub to use a
common %map? why not have them access it directly from the base package?
what is %map used for? understanding that could help with a better solution.
making the empty subs is very easy with closures and symrefs/globs. you
could write a sub that you could pass in a package name and it will scan
that symbol table for the subs you want, find
the missing subs and save a sub ref into the symbol slot.
you could also control the %map access by creating closures where you
pass in the reference to the desired %map. something like:
my $use_map = \%Some::map ;
*{$sub_name} = sub { $use_map->{foo} ... } ;
so after you clarify my brane, we can do a better job with an answer.
uri
_______________________________________________
Boston-pm mailing list
[email protected]
http://mail.pm.org/mailman/listinfo/boston-pm