in reply to Appending to variable with a switch statement?
You can get a nice effect though - and also answer your question about removing the repeated bit of code - by using a dispatch table. Perl has the nice feature of anonymous subroutines/closures, which allow you to write a snippet of code in the middle of another function. These snippets are scalars (since they are references) and so can be stored anywhere you can normally store a scalar, in particular as a hash value.
So you can do things like:
Your code snippets can take arguments (which you'd put in place of the dots in the ->(...) call) and access them in the normal with via @_. They can also do anything code can do (including random sideeffects) rather than just returning a value as above.my %dispatch_table = ( sloven => sub { return sloven('xml'); }, badger => sub { return badger2xml(); }, ); my $case = 'sloven'; my $subref = $dispatch_table{$case}; $responseXML .= $subref->();
All in all, a cool and useful technique.
|
|---|