wanna_code_perl has asked for the wisdom of the Perl Monks concerning the following question:
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Perl OO: Need a concise way of representing operations on an object
by Athanasius (Archbishop) on Nov 04, 2012 at 03:41 UTC | |
by wanna_code_perl (Friar) on Nov 04, 2012 at 09:05 UTC | |
by Athanasius (Archbishop) on Nov 04, 2012 at 14:45 UTC | |
|
Re: Perl OO: Need a concise way of representing operations on an object
by rjt (Curate) on Nov 04, 2012 at 10:25 UTC | |
by wanna_code_perl (Friar) on Nov 05, 2012 at 00:45 UTC | |
|
Re: Perl OO: Need a concise way of representing operations on an object
by Jenda (Abbot) on Nov 04, 2012 at 11:51 UTC |