in reply to Generic/Variable/Dynamic Subroutines? (Not a redefine)
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!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Generic/Variable/Dynamic Subroutines? (Not a redefine)
by mlewando (Initiate) on Aug 21, 2017 at 17:10 UTC | |
by LanX (Saint) on Aug 21, 2017 at 17:17 UTC | |
by shmem (Chancellor) on Aug 21, 2017 at 18:08 UTC | |
by LanX (Saint) on Aug 21, 2017 at 18:19 UTC | |
by shmem (Chancellor) on Aug 21, 2017 at 18:23 UTC | |
|