Skip to content

Instantly share code, notes, and snippets.

@petdance
Created October 2, 2014 20:04
Show Gist options
  • Save petdance/07bb95a911c889a10010 to your computer and use it in GitHub Desktop.
Save petdance/07bb95a911c889a10010 to your computer and use it in GitHub Desktop.
#!/usr/bin/perl
use warnings;
use strict;
use 5.010;
# State variable is declared inside the loop, instantiated once, and counts correctly.
# Prints clicker values of 1, 2, 3, 4, 5
for my $i ( 1..5 ) {
state $foo_clicker;
++$foo_clicker;
say "foo's clicker = $foo_clicker";
}
# State is in an anonymous sub, but only instantiated once, and counts correctly.
# Prints clicker values of 1, 2, 3, 4, 5
my $bar_sub = sub {
state $bar_clicker;
++$bar_clicker;
say "bar's clicker = $bar_clicker";
};
for my $i ( 1..5 ) {
$bar_sub->();
}
# State is in an anonymous sub that is compiled five times, so
# instantiated five times, and counts wrong. This is how subtest()s are done.
# Prints clicker values of 1, 1, 1, 1, 1 because it is reset every time.
for my $i ( 1..5 ) {
my $baz_sub = sub {
state $baz_clicker;
++$baz_clicker;
say "baz's clicker = $baz_clicker";
};
$baz_sub->();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment