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
In reply to Building an anonymous subroutine by BorgCopyeditor
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |