in reply to Cant create a cookie! Please help

What Hot Pastrami said -- for anything that needs to be robust.

On the other hand 're-inventing the wheel' can be an instructive exercise. Makes you appreciate the standard modules all the more when you struggle to cover all the bases as well as they have done.

It's quite possible your code is not working for some reason outside this subroutine. Try substituting a plain-vanilla version:

sub set_cookie { print "Set-Cookie: testkey=testvalue\n"; }
If that doesn't work, your problem lies in the context from which you are calling the routine. E.g. is your http header completed with a blank line before you call this routine?

If it does work, then build up to your more general version step-by-step until you figure out what was breaking your code.

...Then set that all aside as a learning exercise and use CGI; as Hot Pastrami wisely suggests.