Skip to content

Instantly share code, notes, and snippets.

@oodler577
Last active November 11, 2021 18:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oodler577/9ae279734c2377fdc371affe19057d85 to your computer and use it in GitHub Desktop.
Save oodler577/9ae279734c2377fdc371affe19057d85 to your computer and use it in GitHub Desktop.
example of "state" keyword in Perl
0 on 'a' ~> 1
1 on 'b' ~> 2
2 on 'b' ~> 1
1 on 'b' ~> 2
2 on 'a' ~> 0
0 on 'b' ~> 2
2 on 'a' ~> 0
0 on 'b' ~> 2
2 on 'a' ~> 0
0 on 'b' ~> 2
2 on 'a' ~> 0
0 on 'b' ~> 2
2 on 'a' ~> 0
0 on 'a' ~> 1
1 on 'a' ~> 0
use strict;
use warnings;
use v5.10;
sub get_next {
my $char = shift;
state $current = 0;
return $current if not $char;
my $table = {
0 => {
'a' => 1,
'b' => 2,
},
1 => {
'a' => 0,
'b' => 2,
},
2 => {
'a' => 0,
'b' => 1,
}
};
$current = $table->{$current}->{$char};
return $current;
}
my $current_state = get_next;
for my $c ( split //, 'abbbababababaaa' ) {
print qq{$current_state on '$c' ~> };
$current_state = get_next($c);
print qq{$current_state\n};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment