Next Tricks of the Wizards 180

State Machines For NNTP

        %machine = (        
          START => { DEFAULT=> [ \&say_hello, MAIN, ], },
          MAIN  => { group =>  [ \&cmd_group, MAIN],
          ... } ... );
        BEGIN { $STATE = 'START' }
        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;
          }
        }


Next Copyright © 2003 M. J. Dominus