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

Hi Monks,

Another cookie Q.
When does the cookie get created on the client side?
Is it possible to set a cookie value, create the cookie, and then fetch the cookie back to use its value, all in the same script?
i.e. Like this code:
#!/usr/bin/perl -w use strict; use warnings; use CGI qw(:header); use CGI::Cookie; # Create a new cookie my $c = new CGI::Cookie; $c->name("MY_COOKIE"); $c->value("blah"); # Print a html header with the cookie info print header( -cookie=>[$c] ); # Find the value of the cookie we just created my %cookies = fetch CGI::Cookie; if ($cookies{'MY_COOKIE'}) { print $cookies{'MY_COOKIE'}->value; } # end-if exit;
The above code is useless I know, and not in the context of which I am using it. But it does illustrate my Q perfectly.

Also it doesnt work. It only displays the value after the first refresh.

Cheers,
Reagen

Replies are listed 'Best First'.
Re: When are cookies created?
by davorg (Chancellor) on Nov 16, 2004 at 14:50 UTC

    The fetch function extracts cookies from the headers of the HTTP request that lead to your program being executed. Unless you sent out a cookie on a previous invocation of the program then the browser won't have a cookie to send in the headers.

    So, no, you can't access the cookie during the same invocation of the program.

    --
    <http://www.dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: When are cookies created?
by TedPride (Priest) on Nov 16, 2004 at 16:19 UTC
    Just modify the hash returned from CGI::Cookie with the new cookie info. The cookie isn't updated in the browser until the current session is over.