Next Tricks of the Wizards 181

State Machines Are Very Easy to Read!

        sub run_machine {
          for (;;) {
            my $t_table = $machine{$STATE};
            my ($input, @args) = get_input();  
            my ($action, $next_state) = 
              @{$t_table->{$input} || $t_table->{DEFAULT}};
            unless defined($next_state) {        
              die "No transition defined for state $STATE, input $input";
            }
            $action->(@args) if $action;
            $STATE = $next_state;
          }
        }

Capture regularity with code, irregularity with data.



Next Copyright © 2003 M. J. Dominus