[Melbourne-pm] Camel POOP -- initialisation of an object
Jacinta Richardson
jarich at perltraining.com.au
Tue Nov 21 22:07:18 PST 2006
Tim Connors wrote:
> my ($class, %args) = (@_);
> $class = ref($class) || $class;
> my $self = {
> _public => \%fields,
> %fields,
> };
I'm not quite sure what this is supposed to be doing. Why are you storing both
a reference to %fields and the contents of %fields? How will you keep them both
in sync?
Anyway, the answer to your question may be found in Storable's dclone (deep
clone) subroutine:
use Storable qw(dclone);
my $self = {
_public => dclone(\%fields),
%{ dclone \%fields },
};
For example, the following code provides 4 different array references for "c"
and thus, should work as you need it to:
#!/usr/bin/perl -w
use strict;
use Storable qw(dclone);
use Data::Dumper;
my %fields = (
a => 1,
b => undef,
c => [],
);
sub new {
my $self = {
_public => dclone(\%fields),
%{ dclone \%fields },
};
return $self;
}
my $foo = new();
my $bar = new();
print Dumper $foo;
push @{$foo->{c}}, (1, 2, 4);
push @{$foo->{_public}{c}}, (10, 11, 12);
print Dumper $foo;
print Dumper $bar;
> my @keys = sort keys(%args);
> foreach my $key (@keys) {
> $self->$key($args{$key}); #initialise the known values
> }
> return $self;
I'm not quite sure why you sort the keys before doing this loop, it doesn't seem
to gain you anything. Perhaps:
foreach my $key ( keys %args ) {
$self->$key($args{$key} );
}
All the best,
J
--
("`-''-/").___..--''"`-._ | Jacinta Richardson |
`6_ 6 ) `-. ( ).`-.__.`) | Perl Training Australia |
(_Y_.)' ._ ) `._ `. ``-..-' | +61 3 9354 6001 |
_..`--'_..-_/ /--'_.' ,' | contact at perltraining.com.au |
(il),-'' (li),' ((!.-' | www.perltraining.com.au |
More information about the Melbourne-pm
mailing list