http://www.perlmonks.org?node_id=11132395

I needed to save the cookies in HTTP::Cookies into Netscape format (aka 'cookies.txt'). Unfortunately I discovered that this functionality is offered by HTTP::Cookies::Netscape alone, which is a subclass of HTTP::Cookies overriding parent-class's load() and save() methods.

However, if one has no control over the creation of the cookie jar (that is, someone has created it and passed it on to us) then it's a bit of a puzzle on how to do that, easily. Actually I did not find a way apart from doing it manually myself by copy-pasting the contents of HTTP::Cookies::Netscape::save() into my own "static" sub which takes in a HTTP::Cookies and saves it in "Netscape" format. But that's a round-about way which also suffers from missing on any patches on the original code.

What I eventually did was to bless the original HTTP::Cookies object into a HTTP::Cookies::Netscape. Call the save() method, which is now different. And when that's done, bless-back to HTTP::Cookies. I just hope this method is as clean as it looks like without side-effects, provided that nobody touches the object in-between its many blessings.

Here is code demostrating the bless/re-bless:

use HTTP::Cookies; use HTTP::Cookies::Netscape; use LWP::UserAgent; my $cookie_jar = HTTP::Cookies->new(); my $browser = LWP::UserAgent->new( ); $browser->cookie_jar( $cookie_jar ); # hit some pages # now re-bless the cookie jar to obtain ::Netscape functionality bless $cookie_jar => 'HTTP::Cookies::Netscape'; $cookie_jar->save("mycookies.txt"); # and now re-bless back to original bless $cookie_jar => 'HTTP::Cookies';

bw, bliako