in reply to Mapping URLs to code - in search of perlish dispatch schemes
whose class (for all languages/rule sets) would be something like:use AnyLanguage; my @lexicon = [ ( REGEXP => regex1, ACTION => sub { code1 } ), ... ( ACTION => sub { default code } ) ]; my $MyLanguage = AnyLanguage -> new( \@lexicon ); ... while ( my $input = ... ) { $MyLanguage -> dispatch{ $input }; }
Update: Although as MyLanguage expands in complexity and usage, I would at some point in practice go one step further and package up all the 'action' code for language MyLanguage into its own MyLanguage class and simplify the action code into calls to methods of such a class, so that AnyLanguage ceases to be used directly by the 'outer' code, but by the methods in MyLanguage. In that case, the initialisation of the LEXICON for Mylanguage be moved to the new method of the MyLanguage class, before being passed on to the new method of the AnyLanguage class.package AnyLanguage; sub new { my $self = shift; my $self -> { LEXICON } = shift; return bless $self; } sub dispatch{ # match down array and react accordingly my $self = shift; $_ = shift; my $aref = $self -> { LEXICON }; for ( my $i = 0; $i < $#$aref; $i++ ) { my $regexp = $aref -> [$i] -> { REGEXP }; /$regexp/ and return &($aref -> [$i] -> { ACTION }}; } return &{$aref -> [$#$aref ] -> { ACTION }}; } 1;
more update: it is also possible to maintain a separate dispatcher and parser (more likely wrapper for e.g. Parse::RecDescent) in the same AnyLanguage module, using a flag to tell AnyLanguage whether MyLanguage is dispatchable or not, (amongst possibly other flags for such critical language characteristic variations) to avoid having to duplicate code for different statement formats.
-M
Free your mind
|
|---|