Last active
November 11, 2021 18:53
-
-
Save oodler577/9ae279734c2377fdc371affe19057d85 to your computer and use it in GitHub Desktop.
example of "state" keyword in Perl
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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