in reply to Re^2: Really Long if/elsif/else blocks
in thread Really Long if/elsif/else blocks
I'll give it a shot....
my $checks = [ { test => sub { my $state = shift; my $tok = shift; if ($state->{checkPrefix}) { return $state->{base} = &driveBase($canon{$tok}, {%$Args, check +Prefix=>0})); } return; }, action => sub { my $state = shift; my $tok = shift; &equivWord($tok, $cannon{$tok}, {}); }, }, # Check number 2 { test => sub { ... }, action => sub { ... }, }, # and so on # Make your last test succeed (test => sub {1}), # and have your default logic go there. ]; while (my $tok = getTok(...)) { resetState($state); foreach my $check (@$checks) { if ($check->test($state, $tok)) { $check->action($state, $tok); last; } } }
What is nice, is that you can take this to the next level, and break some of your related tests into modules, and write the above in a manner that would allow those modules to register new checks (put $checks setup into registerCheck() and the loop into runChecks).
registerCheck(test => sub {...}, action => sub {...});
I have used this method for testing to see if lists of documents and attributes meet certain criteria, saving state for the entire run, and reporting not only on individual items, but the results of the entire run. The logic looks very similar to what I have above.
--MidLifeXis
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Really Long if/elsif/else blocks
by perreal (Monk) on May 30, 2008 at 22:10 UTC |