Cookies are small pieces of data stored on the client's browser. In Perl, they're commonly used in web applications for session management, user preferences, and tracking.
To create and set cookies in Perl, you'll typically use the CGI
module. Here's a basic example:
use CGI;
my $cgi = CGI->new;
# Set a cookie
print $cgi->header(
-type => 'text/html',
-cookie => $cgi->cookie(
-name => 'user_id',
-value => '12345',
-expires => '+1h'
)
);
This code creates a cookie named 'user_id' with a value of '12345' that expires in one hour.
To read a cookie, you can use the cookie()
method:
my $user_id = $cgi->cookie('user_id');
print "User ID: $user_id\n";
To delete a cookie, set its expiration time to a past date:
print $cgi->header(
-type => 'text/html',
-cookie => $cgi->cookie(
-name => 'user_id',
-value => '',
-expires => '-1d'
)
);
When working with cookies in Perl, keep these tips in mind:
To deepen your understanding of Perl web programming, explore these related topics:
By mastering Perl cookies, you'll be better equipped to handle client-side data and create more interactive web applications.