Create a Object oriented perl class quickly and easily, including get and set and clear methods, with a default values hash and an initialization hash. Object Oriented Perl by Damian Conway section 8.2 (pages 222-235) has a good treatment of this, but doesn't provide workable code. Below is the code to do this.
package Simple;
use Class::MethodMaker
get_set => [qw(a b)],
new_with_init => 'new';
sub init {
my $self = shift;
my %in_args = @_;
my %default_args = ( b => "default");
my %final_args = (%default_args, %in_args);
foreach my $thiskey (keys(%final_args)) {
$self->{$thiskey} = $final_args{$thiskey};
}
return;
}
-------------- in use_it.pl ---------
use Simple;
my $test = new Simple (a=>1);
# now a==1, b==default.
my $test = new Simple (a=>1, b=>2);
# now a==1, b==2.