A Cookie Example With A Visit Counter
#!/usr/bin/perl -w
use strict;
use CGI qw/:standard/;
my $cookie;

# Get cooke values
my %info = cookie('info');

# Set name and visits
my $name = $info{'name'} || param('name');
my $count = $info{'count'} || 0;

if( param('clear_cookie') ) {
    clear_cookie();
    print_form();
} elsif(!$name) {
    print_form();
} else {
    say_hello();
}

#####

sub clear_cookie {
    # Clear cookie if 'clear cookie' box is checked
    $cookie = cookie(-name=>'info',
                        -value=>\%info,
                        -expires=>'-1d');
}

sub print_form {
    # Send proper header
    if( param('clear_cookie') ) {
        print header(-cookie=>$cookie);
    } else {
        print header;
    }

   # Print form
    print start_html('Cookie Example'),
          h1('Welcome to the Cookie Example'),
          start_form,
          'Name: ', 
          textfield(-name=>'name'),
          p,
          submit,
          reset,
          end_form,
          end_html;
}

sub say_hello {
    $info{'name'} = $name;

    $count++;
    $info{'count'} = $count;

    # Set cooke, expires in 60 days
    $cookie = cookie(-name=>'info',
                     -value=>\%info,
                     -expires=>'+60d');

    print header(-cookie=>$cookie),
          start_html("Hello, $name"),
          h1("Hello, $name"),
          "Visit number $count",
          start_form,
          checkbox(-name=>'clear_cookie',
                   -label=>'Clear Cookie'),
          p,
          submit,
          end_form,
          end_html;
}