The following code creates the definition string of a cookie:
$cookieDef = $q->cookie(-name=>'id',-value=>'5923');
In this case, the cookie is called id, and the value is 5923.
However, this statement by itself does not create a cookie on the
client side. Note that cookie definitions are not a part of the HTML
specification, but rather a part of the HTTP standard. In order to
instruct the client create a cookie, the cookie definition must be
included in the header of an HTTP transmission.
In order to create the cookie, the following statement is needed:
print $q->header(-cookie=>[$cookieDef]);
The syntax [$cookieDef] is ``the reference of a list consisting of
a single item of the cookie definition of id.
The following sample code creates a cookie:
#!/usr/bin/perl use CGI; use strict; use warnings; my $q = new CGI; my $cookieDef = $q->cookie(-name=>'id',-value=>'someID'); print $q->header(-cookie=>[$cookieDef]); print $q->start_html; print 'Check your cookies for a definition of id'; print $q->end_html;
Accessing a cookie is much easier. Since the CGI object $q has
full access to the HTTP header, it can extract all the cookie definitions
passed to it. Invoking the cookie method without specifying
a -value retrieves the value of the named cookie.
Invoking cookie without even specifying a name returns a list
of the names of all cookies.