Dear Monks,
I am seeking advice for using WWW::Mechanize in an object. I want to create a module to reduce the complexity of my scripts. The script should do login and logout of a website (and later some more).
Here is the code I wrote:
#!/usr/bin/perl
#
#
use strict;
use warnings;
my $test = TestModule->new( user => 'username', password => 'password'
+ );
print $test->{login};
$test->logout;
package TestModule;
use strict;
use warnings;
use Carp;
use WWW::Mechanize;
use WWW::Mechanize::FormFiller;
use IO::Uncompress::Gunzip qw(gunzip $GunzipError);
sub new {
my $class = shift;
my %passed_params = @_;
my $self = {};
for my $parm ( keys %passed_params ) {
$self->{$parm} = $passed_params{$parm};
}
my $agent = WWW::Mechanize->new( autocheck => 1 );
my $formfiller = WWW::Mechanize::FormFiller->new();
$agent->env_proxy();
$agent->agent_alias('Windows Mozilla');
$self->{agent} = $agent;
bless( $self, $class );
$self->login( $self->{agent} );
return $self;
}
<readmore>
sub login {
my $self = shift;
my $agent = $self->{agent};
my $url = 'http://www.mytestpage.com/';
$agent->get($url);
croak "LOGIN Failed\n" unless ( $agent->content =~ /Welcome/i );
if ( $agent->content =~ /Welcome/i ) {
$self->{login} = 'OK';
$self->{content} = $agent->content;
$self->gwp($agent);
return ( $self, $agent );
}
}
sub logout {
my $self = shift;
my $agent = $self->{agent};
$agent->get("http://www.mytestpage.com/logout");
$self->{content} = $agent->content;
}
sub DESTROY {
my $self = shift;
my $agent = $self->{agent};
$self->logout($agent);
}
1;
Is it a sane approach to add $agent as a property to the object?
Are there other (better) ways?