# file survey.t: use strict; use warnings; use Test::More 'no_plan'; my $configfile = 'test.xml'; my @methods = qw(office mailto text save_as_xml load_from_xml); # try to load our module and create a sample object: use_ok('Survey::Config'); my $config = Survey::Config->new(); isa_ok($config, 'Survey::Config'); # check method calls foreach my $method (@methods) { can_ok($config, $method); } # fill out our object with sample test values: is($config->office('test'), 'test', 'can set the office attribute'); is($config->mailto('test@test.com','dude@test.com'), ['test@test.com','dude@test.com'], 'setting the mailto attribute'); # check object's ability to communicate back to us its attributes: #is($config->text(), ''); # try saving our sample object to file: is($config->save_as_xml($configfile), 1); # try reloading our sample object from file: is($config->load_from_xml($configfile), 1); exit; # ******************************************* # file Survey/Config.pm: package Survey::Config; use strict; use warnings; use XML::Simple; sub new { my $proto = shift; my $class = ref($proto) || $proto; my $self = {}; $self->{OFFICE} = undef; $self->{MAILTO} = []; bless ($self, $class); return $self; } sub office { my $self = shift; if (@_) { $self->{OFFICE} = shift; } return $self->{OFFICE}; } sub mailto { my $self = shift; if (@_) { $self->{MAILTO} = [@_]; } return $self->{MAILTO}; } sub error { my $self = shift; if (@_) { $self->{ERROR} = shift; } return $self->{ERROR}; } sub save_as_xml { my $self = shift; my $configfile = shift; die "No filename specified!" unless $configfile; die "Bad filename!" if $configfile =~ m/[^\w\._-]/i; my %office = $self->_hashkeys; my $xml = XML::Simple->new(); my $text = $xml->XMLout( \%office, rootname => 'config', # noattr => 1, keyattr => 'office', ); open (OUT, '>', $configfile) or die $!; print OUT $text; close OUT; return 1; } sub load_from_xml { my $self = shift; my $configfile = shift; die "No filename specified!" unless $configfile; die "Bad filename!" if $configfile =~ m/[^\w\.-]/i; my %office; my $xml = XML::Simple->new(); my $hr = $xml->XMLin( $configfile, # noattr => 1, keyattr => 'office', forcearray => ['mailto'], ); foreach my $key (keys %{$hr}) { $self->$key($hr->{$key}); } return 1; } sub _hashkeys { my $self = shift; return %{$self}; } 1;