Reputation: 2821
I am not very skilled in Perl, and I am trying to use FSA::Rules. What is the shift doing in this code?
my $fsa = FSA::Rules->new(
ping => {
do => sub {
print "ping!\n";
my $state = shift;
$state->result('pong');
$state->machine->{count}++;
},
rules => [
game_over => sub { shift->machine->{count} >= 20 },
pong => sub { shift->result eq 'pong' },
],
},
pong => {
do => sub { print "pong!\n" },
rules => [ ping => 1, ], # always goes back to ping
},
game_over => { do => sub { print "Game Over\n" } }
);
$fsa->start;
$fsa->switch until $fsa->at('game_over');
Upvotes: 1
Views: 231
Reputation: 234795
The shift
command is accessing the next argument to each subroutine.
The arguments to FSA::Rules->new
is a hash with three keys: ping
, pong
, and game_over
. Let's take ping
: it maps to another hash containing two keys: do
and rules
. The do
key maps to a subroutine:
sub {
print "ping!\n";
my $state = shift;
$state->result('pong');
$state->machine->{count}++;
}
This method expects to be called with an FSA::State
object as the argument. The other subroutines follow similar ideas. Consult the FSA::Rules docs for how to use all this.
Upvotes: 3
Reputation: 4209
By default shift removes and returns the first element of the @_ array. Since that is the parameter array that is passed to subroutines, its getting the first subroutine argument. For example
sub { print shift; }
is an anonymous subroutine that just consumes and prints its first argument.
Upvotes: 4
Reputation: 1043
Shift removes and returns the first element of an array. When the array is not specified, @_ is assumed. @_ in that context is the list of arguments passed to the subroutine.
Upvotes: 2