I want to know how things like Class::MethodMaker and similer things work. Class::MethodMaker creates the subs at compile time. Is it possible to add subs during run time?
Yes, it is possible to do this at runtime. Basically you need to access the symbol table, which can be done like so (altering your code somewhat).
Then you can do the following:sub add_method { my $class = shift; my $name = shift; my $code = shift; no strict 'refs'; # because you should have strict on *{$class . '::' . $name} = $code; }
Of course there are a number CPAN modules you could use to do this; Sub::Install, Sub::Installer, Class::Accessor, etc.# you must call this as a method, and pass it a CODE ref blort->add_method('foo', sub { print 'bar' }); # now you can do this ... blort::foo();
In reply to Re: Sub on the fly?
by stvn
in thread Sub on the fly?
by pileofrogs
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |