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__


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to