I have a Perl OO problem in need of some brevity. Basically, I have three classes:
Container and Record are straightforward, and writing each transformation is relatively easy as well, but I'm struggling to come up with a concise Perl syntax to express each transformation. For example, I have something like this:
# Error checking omitted for brevity... package Foo::Transform; my %transformations = ( # TODO - What goes here? ); sub new { my ($proto, @xforms) = @_; my $class = ref($proto) || $proto; bless({ xforms => [ @xforms ] }, $class); } sub transform { my ($self, $container) = @_; for my $xform (@{$self->{xforms}}) { my $foo = get_foo(); my $bar = get_bar(); # TODO - Apply transformation named $xform # on $container, with $foo and $bar # available as well. } }
I could of course do something like:
my %transformations = ( 'xform1' => sub { my ($cont, $foo, $bar) = @_; ... } );... and then call $transformations{$xform}->($cont,$foo,$bar) in transform(), but the very thing I'm trying to avoid is the needless duplication of that boilerplate in every transformation. Most transformations will just be one or two statements, but some will be rather more complex.
I would like to have $cont, $foo, and $bar automatically available in lexical scope of each transformation, but I don't know if that's possible without using eval EXPR (as opposed to BLOCK syntax), and if I do that I lose compile-time checks, not to mention syntax highlighting. :-)
If there's a better OO/Perl pattern I'm missing here, please let me know! This doesn't smell right.
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |