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


in reply to Dynamically Changing Packages w/out Eval

This doesn't avoid eval, but it shouldn't break syntax highlighting, nor postpone compile issues to runtime:
sub run_in_package (&$) { my($code, $package) = @_; eval "package $package; &$code; 1" or die $@; } foreach my $block ($self->get_blocks) { run_in_package { $block->setup->(); $block->code->(); $block->teardown->(); } $block->package; }

Replies are listed 'Best First'.
Re^2: Dynamically Changing Packages w/out Eval
by betterworld (Curate) on Aug 25, 2009 at 12:11 UTC
    eval "package $package; &$code; 1" or die $@;

    I think you're missing a "\" before "$code". But then the code will be called via a code reference, and the contents of the code reference are still in the old package (where they were compiled):

    sub run_in_package (&$) { my($code, $package) = @_; eval "package $package; &\$code; 1" or die $@; } run_in_package { showcaller(); } 'foooo'; sub showcaller { warn scalar caller; }

    The text of the warning will be "main" (not "foooo").