Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Dynamically Changing Packages w/out Eval

by betterworld (Deacon)
on Aug 24, 2009 at 12:15 UTC ( #790795=note: print w/ replies, xml ) Need Help??


in reply to Dynamically Changing Packages w/out Eval

Some funny code I wrote yesterday (the technique can be probably used for your problem too):

use Symbol qw(qualify_to_ref); use overload; my $stashref = qualify_to_ref("${namespace}::"); package tmp; local *tmp:: = *$stashref; overload->import('+' => sub { my $self = shift; my ($other, $info) = @_; # do some stuff });

This sets up overloaded operators for the namespace with the computed name $namespace.

Note that you cannot use "main" instead of "tmp", because the main namespace seems to be too read-only for this kind of hack (you'd get the error "Modification of read-only value attempted")


Comment on Re: Dynamically Changing Packages w/out Eval
Select or Download Code
Re^2: Dynamically Changing Packages w/out Eval
by ikegami (Pope) on Aug 24, 2009 at 13:41 UTC
    A lot simpler and a lot less fragile:
    my @overload = ('+' => sub { my $self = shift; my ($other, $info) = @_; # do some stuff }); eval "package $namespace; use overload \@overload; 1" or die $@;
      I thought the original question was how to avoid eval :)
        You can't expect someone to read the OP
        True, but he wanted to avoid eval "because it obfuscates the code". It's clearly the opposite here.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://790795]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (6)
As of 2015-07-04 09:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (59 votes), past polls