Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm currently using the code below to retrieve specific information from a cookie.
use CGI::Cookie; %cookies = fetch CGI::Cookie; my $isset = $cookies{'user'}; my @temp1 = split(/\;/, $isset); my @temp2 = split(/=/, $temp1[0]); my $username = $temp2[1];
I don't have a lot of experience with perl, but I'm sure there's an easier way to retrieve a cookie value. The code above is used to retrieve a cookie named user. Then I need to retrieve the value from that cookie named username. Unfortunately the only way I know how to do this is by splitting the $isset variable. Any suggestions?

Replies are listed 'Best First'.
Re: retrieving cookies with CGI::Cookie
by ikegami (Patriarch) on Sep 25, 2005 at 04:46 UTC

    You should be using value, as per the documentation. value returns a hash when the a hash was used to create the cookie.

    %user_data = $cookies{'user'}->value; print($user_data{field1}, "\n"); print($user_data{field2}, "\n");

    assuming you used the following to create it:

    $user_cookie = new CGI::Cookie( -name => 'user', -value=> { field1 => 'value1', field2 => 'value2', } )

    By the way, the cookie will look something like:

    user=field1&value1&field2&value2; path=/
Re: retrieving cookies with CGI::Cookie
by nedals (Deacon) on Sep 25, 2005 at 14:56 UTC
    use strict; use CGI; my $q = new CGI; my $username = $q->cookie('username');