# Code snippet for Web Programming at 2012/12/10,
# slide at http://zoro.ee.ncku.edu.tw/wp2012/res/11-cookie.pdf
################################################################################
# form version (with CGI)
#!/usr/bin/perl -w
use strict;
use CGI;
use CGI::Cookie;
use YAML;
my $cgi = new CGI;
if ( defined $cgi->param('state') ) {
# the 'state' should match the term used in
&render(int($cgi->param('state'))+1);
# you should use this parameter to load something for calculation,
# rather than calculate it directly
} else {
&render(0); # initialize
}
sub render {
my $state = shift;
print "Content-type: text/html\n\n";
print <
END
# notice the type="hidden", which is usually used in this codition
# can we use method="get" here?
}
# vi:nowrap:sw=2:ts=2
################################################################################
# cookie version (with CGI)
#!/usr/bin/perl -w
use strict;
use CGI;
use CGI::Cookie;
my $cgi = new CGI;
@_ = $cgi->param('keywords');
# a special technique in Perl CGI module, try Dump($cgi)
if ( 1 == @_ ) {
print "Set-Cookie: state=$_[0];\n"; # notice the 'state'
print "Content-type: text/plain\n\n";
print "Set state to $_[0].";
# you should name 'state' as, for example, 'session_id' and
# save something with $_[0], such as a file named with $_[0]
} else {
my $state = $cgi->cookie('state');
# the 'state' should match the term used in 'Set-Cookie'
print "Content-type: text/plain\n\n";
print "The state is $state.";
# load something with $state
}
# vi:nowrap:sw=2:ts=2
################################################################################
# JavaScript version (without CGI)
Cookie demo