BorgCopyeditor has asked for the wisdom of the Perl Monks concerning the following question:
Yesterday, I finally figured out what a closure was, at the same time that I figured out that I might have a use for one. I have a subroutine that encodes a (usually long) list of words into a given character-encoding scheme that depends on a user's preference.
Currently my subroutine stupidly checks what the user's configuration was set to for each word. I thought it would be more reasonable to use the configuration option to produce the appropriate subroutine once and for all at the beginning of the program, like so:
$encode = 'u'; # example, could be 'p', 'b', or 'u' $sub_ref = template($encode); sub template { my $e = shift; if ($e eq 'b') { return sub {...stuff...} } elsif ($e eq 'u') { return sub {...other stuff...} } else { return sub {...yet more...} } } ...time passes... $encoded_output = &$sub_ref;
The problem I'm facing now is that "stuff", "other stuff", and "yet more" share a fair number of common elements. My question is whether there is some simple way to build up the pieces of an anonymous subroutine, such that they could be assembled at the right time.
My current approach will probably be something like this:
sub template { my $e = shift; my $common = sub {...shared stuff...} if ($e eq 'b') { return sub {&$common; ...stuff...} } if ($e eq 'u') { return sub {&$common: ...other stuff...} } etc.
This way, I don't have to type the common pieces of code (and there are a few) into each of the cases. Does this seem like a reasonable way to "build" the pieces of such a function? Are there other ways to do this that make mine look like "baby Perl"?
BCE
--RezistenceResistance is futile.
Title edit by tye
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Closures
by Aristotle (Chancellor) on Aug 11, 2002 at 04:53 UTC | |
by BorgCopyeditor (Friar) on Aug 11, 2002 at 06:19 UTC | |
Re: Building an anonymous subroutine
by Basilides (Friar) on Aug 12, 2002 at 10:07 UTC | |
by mem (Acolyte) on Aug 12, 2002 at 12:29 UTC | |
by Anonymous Monk on Aug 13, 2002 at 00:37 UTC | |
Re: Building an anonymous subroutine
by oylee (Pilgrim) on Aug 12, 2002 at 19:45 UTC | |
Re: Building an anonymous subroutine
by thunders (Priest) on Aug 12, 2002 at 11:06 UTC | |
Re: Building an anonymous subroutine
by stephen (Priest) on Aug 13, 2002 at 03:22 UTC | |
by Anonymous Monk on Aug 13, 2002 at 12:39 UTC | |
Re: Building an anonymous subroutine
by BorgCopyeditor (Friar) on Aug 13, 2002 at 14:20 UTC |