Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Re: Iteration condition...

by radiantmatrix (Parson)
on Mar 31, 2008 at 19:50 UTC ( #677627=note: print w/replies, xml ) Need Help??

in reply to Iteration condition...

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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://677627]
[erix]: s/dawn/dusk/
[erix]: (you're welcome :P)
[james28909]: you know, i had a thought a few mnths back. what if this universe were just a puzzle, waiting for life to figure it out!
[james28909]: what if one day we are able to grab the curtain that is "spacetime" and pull it back to reveal <insert imagination here> pulling at levers and ropes xD
[holli]: like dorothy?
[james28909]: see ya later holli
[james28909]: yeah like wizard of oz lol. its just a joke though
[james28909]: i cannot understand how someone cant see that a cloud of gas that evolves into a solar system or galaxies. it just makes sense to me. everythign that has happened, had to have happened for anything on this planet to be.
[james28909]: /gas/gas and debris/
[james28909]: another thing, i used to be atheist. life experiences, personal evidence. and my own perception is the reason why i believe the things i do.

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (13)
As of 2017-12-15 14:46 GMT
Find Nodes?
    Voting Booth?
    What programming language do you hate the most?

    Results (433 votes). Check out past polls.