Angel has asked for the wisdom of the Perl Monks concerning the following question:

I read many of the OO posts and seem to have missed passing an inital array on the new() function.

http://www.perlmonks.com/index.pl?node=perlman%3Aperlbot has passing the values/scalars as a hash. But not as an array.

What I am trying to do is pass a db handle to an object on creation so that the methods inside can use if for talking to a database.
#example: sub foo ( $self = shift; my $dbh = $self->{$dbh}; $dbh->do{ DELETE FROM EXAMPLE } }

Replies are listed 'Best First'.
Re: Initial Variables
by tadman (Prior) on Nov 25, 2002 at 18:38 UTC
    I find it's easy to make a method like that as long as you're importing hash-style parameters. For example:
    sub new { my $class = shift; my $self = { @_ }; return bless($self, $class); } # ... my $test = Foo->new(handle => $dbh); my $handle = $test->{handle};
    If you're paranoid about what kind of data someone's going to pass in, you can always filter it.
    my @imports = qw [ foo bar ]; sub new { my ($class, %params) = @_; my %self; @self{@imports} = @params{@imports}; return bless(\%self, $class); }
    This will restrict parameters to those in the import list. You could extend this to produce errors, of course.
Re: Initial Variables
by thinker (Parson) on Nov 25, 2002 at 18:33 UTC
    Hi Angel,

    have you considered passing the db handle in as a key => value pair, like
    my $foo=new foo(handle=>$dbh, bar=>"baz", ...);

    then you can assign it to a hash in new(), as in the example you gave.

    Of course, really that is just passing it in as an array (or list), but you don't have to think of it that way. :-)

    Hope this helps

    thinker