for my $meth (qw/ WriteLine Select Add /) { my $sub = sub { my $self = shift; my $it = $self->OStream->$meth($_[0]); $self->Trace(_CallerStr($it)); return $it; }; no strict 'refs'; *$meth = $sub; }
In this loop $meth and $sub form a so called closure, each instance of $sub is "closing over" a new instance of the lexical var $meth with a string.
This my $it = $self->OStream->$meth($_[0]); takes advantage of the fact that method calls are (contrary to sub calls) late evaluated strings, i.e. resolved at runtime. (for completeness $meth could also be a code_ref but that's not relevant here)
This
no strict 'refs'; *$meth = $sub;
is assigning a code_ref in $sub to the symbol named in $meth via a so called *glob.
That's how the STASH (Symbol Table hASH) works, each varname in a package has a hash key and the value is a "typeglob" with 6 so called "slots". Assigning a code_ref fills the CODE-slot, you can also address other slots like SCALAR, HASH or ARRAY and so on.
This case showed how to fill the %main:: stash, other namespaces need to be provided explicitly.
no strict 'refs' was necessary because using symbolic references like in *$meth (i.e. $meth is a string not a pointer like reference) is forbidden under strict.
This would work right away ...
*pack::name = sub {};
... but your name has to be dynamic.
Cheers Rolf
(addicted to the Perl Programming Language and ☆☆☆☆ :)
Je suis Charlie!
In reply to Re: Generic/Variable/Dynamic Subroutines? (Not a redefine)
by LanX
in thread Generic/Variable/Dynamic Subroutines? (Not a redefine)
by mlewando
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |