Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Comment on

( #3333=superdoc: print w/replies, xml ) Need Help??

I don't know about "shorter, more economical", but perhaps easier to maintain:

## a dispatch table in the form state => CODEref my %operation = ( 1 => \&do_this, 0 => \&do_that, 9 => \&do_another_thing, ); ## a table of transitions in the form pattern => state my @transition = ( [ $Start => 1 ], [ $Finish => 0 ], [ $Break => 9 ], ); my $State = 0; # or whatever your initial state is. for my $item (@Input) { # check transition conditions in order; if met, change state for my $trans (@transition) { next unless $item =~ /$trans->[0]/; $State = $trans->[1]; last; } $operation->{$State}->(); # dereference and execute op for this S +tate }

That's a very simple state machine that uses a dispatch table. It's pretty easy to expand: add transitions to the @transition structure, write a sub for each operation and add it to the %operation dispatch table. You don't need to change any other code.

However, if you have a large number of states and/or transitions, using one of the state-machine modules that CountZero references above could be a better choice.

Ramblings and references
The Code that can be seen is not the true Code
I haven't found a problem yet that can't be solved by a well-placed trebuchet

In reply to Re: Iteration condition... by radiantmatrix
in thread Iteration condition... by abachus

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?

    What's my password?
    Create A New User
    and !@monks...

    How do I use this? | Other CB clients
    Other Users?
    Others perusing the Monastery: (6)
    As of 2018-04-26 23:24 GMT
    Find Nodes?
      Voting Booth?