Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: General pattern for interactive text-mode script?

by pc88mxer (Vicar)
on Jul 03, 2008 at 18:50 UTC ( #695438=note: print w/ replies, xml ) Need Help??


in reply to General pattern for interactive text-mode script?

Here's a simple FSM implementation. Each subroutine returns the next 'state' (just a subroutine name) to pass control to. To exit, return undef.

my $state = "start"; while (my $next = $state->()) { $state = $next; } sub start { ...get input... if (/1/) { return "menu_1" } elsif (/2/) { return "menu_2" } ... } sub menu_1 { ... } sub menu_2 { ... }


Comment on Re: General pattern for interactive text-mode script?
Select or Download Code
Re^2: General pattern for interactive text-mode script?
by wazoox (Prior) on Jul 04, 2008 at 10:38 UTC
    Hu, this breaks strictures, better use code references :
    use strict; use warnings; my $state = \&start; while (my $next = $state->()) { $state = $next; } sub start { ...get input... if (/1/) { return \&menu_1 } elsif (/2/) { return \&menu_2 } ... } sub menu_1 { ... } sub menu_2 { ... }
    By the way instead of chaining multiple if () {} blocks, using a dispatch table is more efficient and looks nicer:
    use strict; use warnings; my $state = \&start; while (my $next = $state->()) { $state = $next; } sub start { my %next_action = ( 1 => \&menu_1, 2 => \&menu_2, 3 => \&menu_3, ); return $next_action{$_} if exists $next_action{$_} }

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://695438]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (16)
As of 2015-07-02 17:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (44 votes), past polls