| 1 | package Trigger; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use 5.8.1; | ||
| 5 | our $VERSION = '0.02'; | ||
| 6 | |||
| 7 | use base qw(Class::Accessor::Fast); | ||
| 8 | |||
| 9 | sub new { | ||
| 10 | my $class = shift; | ||
| 11 | my $self = $class->SUPER::new(); | ||
| 12 | $self->mk_accessors(qw/heap _process _trigger _action _trigger_and_action _end/); | ||
| 13 | |||
| 14 | my $args = { | ||
| 15 | #inline_states => {}, | ||
| 16 | @_ | ||
| 17 | }; | ||
| 18 | |||
| 19 | if( my $inline_states = delete $args->{inline_states} ){ | ||
| 20 | $args = { | ||
| 21 | heap => {}, | ||
| 22 | init => undef, | ||
| 23 | process => sub { 1 }, | ||
| 24 | trigger_and_action => [], | ||
| 25 | end => undef, | ||
| 26 | %{$inline_states} | ||
| 27 | }; | ||
| 28 | } | ||
| 29 | |||
| 30 | $self->heap($args->{heap}) if defined $args->{heap}; | ||
| 31 | $self->_process($args->{process}); | ||
| 32 | $self->_trigger([]); | ||
| 33 | $self->_action([]); | ||
| 34 | $self->_end($args->{end}); | ||
| 35 | $self->_trigger_and_action( scalar @{$args->{trigger_and_action}} ); | ||
| 36 | $self->_trigger_and_action % 2 and die ; | ||
| 37 | while( @{$args->{trigger_and_action}} ){ | ||
| 38 | my($trigger, $action) = splice @{$args->{trigger_and_action}}, 0, 2; | ||
| 39 | push @{$self->_trigger}, $trigger; | ||
| 40 | push @{$self->_action} , $action; | ||
| 41 | } | ||
| 42 | $self->_trigger_and_action( $self->_trigger_and_action / 2 - 1); | ||
| 43 | $args->{init}->($self) if defined $args->{init} and ref $args->{init}; | ||
| 44 | return $self; | ||
| 45 | } | ||
| 46 | |||
| 47 | sub eval{ | ||
| 48 | my $self = shift; | ||
| 49 | my @action_re; | ||
| 50 | my @process_re = $self->_process->($self => @_); | ||
| 51 | for ( 0 .. $self->_trigger_and_action ){ | ||
| 52 | if( my @trigger_re = $self->_trigger->[$_]->($self => @process_re) ){ | ||
| 53 | if( ref $self->_action->[$_] eq 'CODE' ){ | ||
| 54 | @action_re = $self->_action->[$_]->($self => @trigger_re) ; | ||
| 55 | }elsif( ref $self->_action->[$_] eq 'ARRAY' ){ | ||
| 56 | for my $code( @{$self->_action->[$_]} ){ | ||
| 57 | @action_re = $code->($self => @trigger_re); | ||
| 58 | } | ||
| 59 | }else{ | ||
| 60 | die ref $self->_action->[$_]; | ||
| 61 | } | ||
| 62 | } | ||
| 63 | } | ||
| 64 | @action_re ? return @action_re : return @process_re; | ||
| 65 | } | ||
| 66 | |||
| 67 | sub DESTROY{ | ||
| 68 | my $self = shift; | ||
| 69 | $self->_end->($self) if $self->_end; | ||
| 70 | delete $self->{$_} for (keys %{$self}); | ||
| 71 | } | ||
| 72 | |||
| 73 | 1; | ||
| 74 | __END__ |