Wiggins D'Anconia wrote: > Dan Anderson wrote: > > > I have a package which I wanted to make an object, so I had something > > like the following: > > > > sub new { > > my $proto = shift; > > my $class = ref($proto) || $proto; > > my $self; > > $self->{BOOL_1} = 0; > > $self->{BOOL_2} = 0; > > # etc... > > while (shift) { > > $self->{$_} = 1; > > } > > bless $self, $class; > > } > > > > The above code wouldn't work unless I did the following: > > > > What doesn't work about it? I couldn't see anything wrong > with it. You might try dumping the reference you store this > into with Data::Dumper...
This looks like it's supposed to be called as my $object = Package->new(qw/BOOL_1 BOOL_2/) where the parameters just list the names of the options to be set to true instead of false. Is that how you're calling it? Otherwise it looks OK as Wiggins says. > > sub new { > > my $proto = shift; > > my $class = ref($proto) || $proto; > > my $self = { > > BOOL_1 => 0, > > BOOL_2 => 0, > > #etc... > > }; > > bless $self, $class; > > while (shift) { > > $self->{$_} = 1; > > } > > } > > > > I then got undefined errors unless I added a bless $self, $class; > > to the last line of the function. Is there an easier way to set options > > within an object's constructor? > > > > This is a *perfect* example of the need to be explicit about return > values in subroutines. The 'bless' in the first is returning the > referent which is then returning it as the value of the 'return' for > the function. Rather than a second 'bless' try adding a 'return $self' > to the end instead. I bet this will fix you up... The classic way to set up defaults which may be redefined is sub new { my $proto = shift; my $class = ref($proto) || $proto; my %self = { BOOL_1 => 0, BOOL_2 => 0, @_, }; bless \%self, $class; } which can then be called as my $object = Package->new(BOOL_2 => 1, NODEFAULT => 99) so that $object is a blessed pointer to a hash that looks like { BOOL_1 => 0, BOOL_2 => 1, NODEFAULT => 99, } I hope this helps. Rob -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]