On Thursday, October 16, 2003, at 02:35 PM, 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 isn't a reference to a hash, even though you're about to start using it like one.


my $self = { };

  $self->{BOOL_1} = 0;
  $self->{BOOL_2} = 0;
        #  etc...
  while (shift) {
    $self->{$_} = 1;
  }

This tears values off of @_, doesn't store them anywhere, but uses the $_, which has who knows what in it here.


$self->{ shift() } = 1 while @_;

  bless $self, $class;
}

The above code wouldn't work unless I did the following:


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; }

Same warning as above.


Plus, you don't return a reference to the object here.

}

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?

sub new { my $proto = shift; my $self = { BOOL_1 => 0, BOOL_2 => 0, @_ }; bless $self, ref($proto) || $proto; }

# call ...
my $object = Class->new(BOOL_3 => 1, etc...);

Hope that helps.

James


-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]



Reply via email to