develooper Front page | perl.beginners | Postings from July 2006

Re: non fixed number of properties in constructor

Thread Previous
From:
Mumia W.
Date:
July 19, 2006 07:09
Subject:
Re: non fixed number of properties in constructor
Message ID:
44BE25BD.1020802@earthlink.net
On 07/19/2006 05:04 AM, Ken Perl wrote:
> ok, let me explain what I mean.
> $account = new Account;
> then I can get the currency of the two countries,
> $account->currency_us;
> $account->currency_fr;
> 
> after I freeze the code, a new country jumps out, suppose i need
> support Iraq, but now I can't use this,
> $account->currency_iraq;
> If I want to support this method, I have to modify the constructor
> again to add the new country, but what I am looking for is the
> solution that doesn't need to modify the constructor again.
> 


You should install Class::Accessor from CPAN (or your Debian 
CD's if you have Debian), and use Class::Accessor as a base 
class to your 'Account' class.

Override new so that it calls mk_accessors for all of the keys 
in the hash you give to new(). With Class::Accessor, what you 
want to do becomes child's play:

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

my $obj = Person4->new({
         height => "4.10",
         name => 'John Gateway',
     });
print Dumper($obj);
exit;

package Person4;
use base 'Class::Accessor';

sub new {
     my ($class, $href) = @_;
     my $self = {};
     bless ($self, $class);
     if ($href) {
         my @keys = keys %$href;
         __PACKAGE__->mk_accessors(@keys);
         $self->$_($href->{$_}) for (@keys);
     }
     $self;
}

__HTH__


Thread Previous


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About