A.5 Handling Cookies

Unless you use a module such as CGI::Cookie or Apache::Cookie, you need to handle cookies yourself. Cookies are accessed via the $ENV{HTTP_COOKIE} environment variable. You can print the raw cookie string as $ENV{HTTP_COOKIE}. Here is a fairly well-known bit of code to take cookie values and put them into a hash:

sub get_cookies {
    # cookies are separated by a semicolon and a space, this will
    # split them and return a hash of cookies
    my @rawCookies = split /; /, $ENV{'HTTP_COOKIE'};
    my %cookies;

    foreach (@rawCookies){
        my($key, $val) = split /=/, $_;
        $cookies{$key} = $val;

    return %cookies;

And here's a slimmer version:

sub get_cookies {
    map { split /=/, $_, 2 } split /; /, $ENV{'HTTP_COOKIE'};

    Part I: mod_perl Administration
    Part II: mod_perl Performance
    Part VI: Appendixes