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

Hi, i have a question. Is there a way to use the $mech->clone function except to save it to a file and load it for later use?

Replies are listed 'Best First'.
Re: WWW::Mechanize clone
by Fletch (Bishop) on Jun 05, 2007 at 03:56 UTC

    Erm, what exactly would you expect to be saved? Aside from cookies (which you can arrange to be saved by creating your own HTTP::Cookies instance and passing that to your mech instance's cookie_jar method) I'm not thinking of a whole lot worthwhile state that you could save (I mean maybe the history of what URLs you fetched, but if you grabbed it once you could grab it again (and probably would want to to get the most up-to-date contents) . . .).

    Perhaps if you described in more detail exactly what you think you'd gain by serializing a mechanize instance to disk you might get more cogent help.

      Ok, what im trying to do is get mech to submit a form return a captcha form me to input and then continue submitting the captcha. I got this to work through the console but im trying to get it to work through the browser with cgi. Now my problem is after i input the captcha i loose all the information stored in the $mech object. Ive spent hours (newb) fiddling with HTTP::Cookies but so far i only managed to save it to a file and not sure if its even the right cookies. So i read some more and found out it might be possible to dump the whole $mech object to a file and load it later i guess with using YAML. Actually i just tried
      YAML::DumpFile('../data/saved.dat', $mech);
      And it worked it saved everything that was in the $mech now how do i load this for further use? or is there an easier method of accomplishing what im trying to do?

        At any rate it saved most of it. If you look at the YAML itself you'll see that it didn't get everything, specifically the onerror and onwarn callbacks:

        ... onerror: !!perl/code: '{ "DUMMY" }' onwarn: !!perl/code: '{ "DUMMY" }' ...

        So if you were doing anything special with these handlers you'd want to re-set them ($mech->{onerror} = sub { ... }; there's no API for changing these post-constructor so you've got to break encapsulation) after you've used YAML::LoadFile to read it back in. And I'd still be wary there might be other similar brittleness that I'm not seeing just serializing a brand new, unused instance.

        Update: Or try using YAML::Syck instead and set $YAML::Syck::UseCode = 1; however that'll still have problems if the coderefs in question are closures (since the enclosing lexical context is long gone).

        perldoc YAML Load