Skip to content

Instantly share code, notes, and snippets.

@s1037989
Created February 15, 2016 09:31
Show Gist options
  • Save s1037989/179d53b86e46ae788f62 to your computer and use it in GitHub Desktop.
Save s1037989/179d53b86e46ae788f62 to your computer and use it in GitHub Desktop.
Demonstration of the use of a state variable in a Mojolicious app
#!/usr/bin/env perl
package A;
use Mojo::Base -base;
use 5.020;
use feature qw(signatures);
has [qw(a b)];
sub new {
my $self = shift->SUPER::new(@_);
warn 'new';
$self;
}
sub c ($self) { $self->a + $self->b }
package main;
use Mojolicious::Lite;
helper a => sub { warn 'a'; A->new(a => $_[1], b => $_[2]) }; # Always re-call A->new
helper b => sub { warn 'b'; state $a = A->new(a => $_[1], b => $_[2]) }; # if state $variable is already set, just it and don't use it again. Or:
helper c => sub { warn 'c'; shift->{_state} ||= A->new(a => $_[0], b => $_[1]) }; # b & c are equivalent
get '/' => sub {
my $c = shift;
warn "!! A\n";
warn $c->a(1,2)->c; # 3
warn $c->a(2,3)->c; # 5 (NOTE!)
warn "!! B\n";
warn $c->b(3,4)->c; # 7
warn $c->b(4,5)->c; # 7
warn "!! C\n";
warn $c->c(5,6)->c; # 11
warn $c->c(6,7)->c; # 11
$c->render(text => scalar localtime);
};
app->start;
__END__
!! A
a at state.pl line 20.
new at state.pl line 12.
3 at state.pl line 27.
a at state.pl line 20.
new at state.pl line 12.
5 at state.pl line 28.
!! B
b at state.pl line 21.
new at state.pl line 12.
7 at state.pl line 30.
b at state.pl line 21.
7 at state.pl line 31.
!! C
c at state.pl line 22.
new at state.pl line 12.
11 at state.pl line 33.
c at state.pl line 22.
11 at state.pl line 34.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment