in reply to Hiding, but maintaining variables in user-defined code

Masem, maybe I miss something here. But, by the very definition of OOP, the user already knows what $self is: It is the very object that (s)he is calling. In this case, $test. What else do you want?

For globals and the like, just store everything in the $self={} hash, unless they are package globals. In either case, keep the interface clean by not letting the user access the $self hash and the globals directly. Use methods for that instead. So if you have a $self->{evil_case}->{unit666}=0, I would write a method $self->IsDevilPresent() that returns the zero. Your user code would than be:

$test->execute( { print "This is user code\n"; die "The devil is in $test->name()! I can't live with that!" if $test->IsDevilPresent(); } );
So in general, hide the implementation from the user. Keep the interface clean and the subroutines independent.

Hope this helps,

Jeroen
"We are not alone"(FZ)
Update: On the bike to work, my lightbulb went on (ask tilly about it ;-). You don't want to call the $test from the sub, but you want the dynamic $self from the package. So the code becomes:

$test->execute( { my $self = shift; print "This is user code\n"; die "The devil is in $self->name()! I can't live with that!" if $self->IsDevilPresent(); } ); #In the package, you must supply $self as an arg: return &$coderef( $self );

Replies are listed 'Best First'.
Re: Re: Hiding, but maintaining variables in user-defined code
by bwana147 (Pilgrim) on May 23, 2001 at 11:44 UTC

    And what about allowing extra arguments for execute, simply by passing to the coderef whatever is left in @_?

    # in the class package sub execute { my $self = shift; my $coderef = shift; return &$coderef($self, @_); } # in the main $test->execute(sub { my $self = shift; # do something with the rest of @_ }, $arg1, $arg2);
    --bwana147