in reply to Technique for building arguments from function name?
This is likely a sign of need for designing things in a more general way (subclass or something). However, sometimes there's already an established API to follow, and generalization is only available under the hood. In such cases I do like follows:
package Bark; use strict; use warnings; # more code here foreach (qw(cat dog)) { my $method_name = "function_$_"; # We're going to close over this variable # so it must be fresh in every loop iteration # don't use loop counter here my $impl = $_; # pre-caclucate more variables here if needed. # do whatever normal "sub $method {...}" would do # while we're still in strict mode my $code = sub { print $impl; }; # Finally, plant method - stricture is ONLY turned off # until end of scope i.e. for 1 line only no strict 'refs'; ## no critic # just in use "perlcritic" *$method_name = $code; }; 1;
This code can be tested (and actually was) with the following line:
perl -I. -MBark -we 'Bark->function_cat'
Note that I use $_ as loop variable because I have to reassign it anyway or ALL generated closures refer to the same var.
This sample is possibly in for further improvements but at least it allows to generalize code and have strictures on in the generated method/functions.
|
|---|