in reply to session variables

it looks to me that be the time you do (Line 47)
print $cgi->header(-cookie=>$cookie);
it's too late, because you've already sent you header with (Line 26)
print $cgi->header;
Have a look at the tutorial and the cookbook