The following "set_cookie.pl" program shows how to set cookies in perl:
#!/usr/bin/perl
use CGI;
my $cgi = new CGI;
# creating cookies by specifying name and value for the cookie items with lifespan of the cookies set to 1 hour
my $cookie_1 = $cgi->cookie( -name => 'friend_name', -value => 'James Dcosta', -expires => '+1h');
my $cookie_2 = $cgi->cookie( -name => 'friend_age', -value => '36', -expires => '+1h');
# setting the cookies via response header
print $cgi->header( -cookie => [$cookie_1, $cookie_2] );
print "Cookie Set";
The following "read_cookie.pl" program will read the cookie values set in the earlier program:
#!/usr/bin/perl
use CGI;
my $cgi = new CGI;
print $cgi->header();
# reading the cookie values via CGI object
my $friend_name = $cgi->cookie('friend_name');
my $friend_age = $cgi->cookie('friend_age');
print "Reading values from cookies
";
print "Friend Name: ".$friend_name."
";
print "Friend Age: ".$friend_age."
";
Output:
-------
On calling the "set_cookie.pl" program from browser, it will set friend name and age in cookies named 'friend_name' and 'friend_age' respectively and then on calling the "read_cookie.pl" program from browser, it will read the cookies named 'friend_name' and 'friend_age' set earlier and display on the screen.
