perl finite state diagram

perl finite state diagram
For a diagram, the language is irrelevant. Since it’s the topic, let’s do a really minimal finite state machine, or DFA, with Perl. This one goes into or remains in accept state with the input of “x” and goes or remains out of accept with any other input. If called without input, it returns its current state for examination.
To sweeten the pot, as it were, we’ve added a cool trick with Scalar::Util::dualvar which lets us assign a human value, “not accept,” along with a mathematical value, “0,” to the same variable. The context, numeric or string (%d or %s in our printf), decides which we’ll get back and we could use it to mix truth tests with something a user could easily follow.
use Scalar::Util 'dualvar';
my $dfa = make_dfa();
my @input = qw( qwer 0 1 x CAT X x 3.14 );
for my $input ( @input ) { $dfa->($input); printf("%15s --> %-10s (%d)\n", $input, $dfa->(), $dfa->(), ); }
exit 0; #============================================ sub make_dfa { my $accept = dualvar(1,'accept'); my $not_accept = dualvar(0,'not accept'); my $state = $not_accept;
return sub { my $input = shift; return $state unless $input; $state = $input eq 'x' ? $accept : $not_accept; } } __END__ ________ x ========== ___ --->| |------->|| ||/ \ !x/ | not | || accept || / x \___/| accept |<-------|| ||<--- -------- !x ==========
When we run it, we get:
           qwer --> not accept (0)
              0 --> not accept (0)
              1 --> not accept (0)
              x --> accept     (1)
            CAT --> not accept (0)
              X --> not accept (0)
              x --> accept     (1)
           3.14 --> not accept (0)
[close] Permanent link · http://querylog.com/q/perl+finite+state+diagram

Suggested HTML for linking:
Link preview: perl finite state diagram
30 July 2005 · Internet & computing
The page found by the original query:
Finite automata in Perl
Browse by the page—15 Q&R each
« previous | more »